I try to following CGAL example in Qt widget application :
example
main.ccp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.ccp :
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
void MainWindow::on_pushButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Open .off model"), "/home", tr("*.off"));
draw_poly(fileName);
}
void MainWindow::draw_poly(QString fileName)
{
QByteArray inBytes;
const char *c;
inBytes = fileName.toUtf8();
c = inBytes.constData();
std::ifstream input(c);
if (!input || !(input >> mesh) || mesh.is_empty()) {
std::cerr << "Not a valid off file." << std::endl;
// return 1;
}
input >> mesh;
CGAL::draw(mesh);
}
when I ran it , it open dialog file to select .off file ,then it shows the following error:
QCoreApplication::exec: The event loop is already running
any help ,please ?
I'm using Qt5 in daily business, and once considered CGAL as possible application base (without going further into this direction – not yet). Hence, this question made me curious.
I digged through the source code of CGAL on github and found out why the error message
QCoreApplication::exec: The event loop is already running
occurs.
For this, I copied the relevant lines from CGAL on github: Polyhedron/include/CGAL/draw_polyhedron.h:
template<class Polyhedron, class ColorFunctor>
void draw(const Polyhedron& apoly,
const char* title,
bool nofill,
const ColorFunctor& fcolor)
{
#if defined(CGAL_TEST_SUITE)
bool cgal_test_suite=true;
#else
bool cgal_test_suite=false;
#endif
if (!cgal_test_suite)
{
int argc=1;
const char* argv[2]={"polyhedron_viewer","\0"};
QApplication app(argc,const_cast<char**>(argv));
SimplePolyhedronViewerQt<Polyhedron, ColorFunctor>
mainwindow(app.activeWindow(), apoly, title, nofill, fcolor);
mainwindow.show();
app.exec();
}
}
Looking at this source code, it becomes obvious that CGAL::draw() is a small ful-featured Qt application in itself which establishs its own QApplication instance. The OP in turn tried to embed the CGAL::draw() in her/his own Qt application. It is not allowed to instance any derivates of QCoreApplication more than once (according to Qt doc. of QApplication):
For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time.
(Emphasizing not mine.)
The CGAL doc. provides an (even shorter) example in Polyhedron/draw_polyhedron.cpp to do this right:
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
int main(int argc, char* argv[])
{
Polyhedron P;
std::ifstream in1((argc>1)?argv[1]:"data/cross.off");
in1 >> P;
CGAL::draw(P);
return EXIT_SUCCESS;
}
but there is no place to insert the QFileDialog at the right point.
Hence, CGAL::draw() is the wrong tool for what OP (probably) intends to do – embed CGAL polyhedron rendering into a Qt application. For this, it is necessary to use the things directly which are called somewhere inside of CGAL::draw().
So, this is what seems appropriate to me:
making SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> a (main or child) widget in OPs Qt application.
I then walked a bit through the github repo to find out from which Qt widget CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> is actually derived from and found the following inheritance:
CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor>
|
V
CGAL::Basic_viewer_qt
|
V
CGAL::QGLViewer
|
+--------------+--------------+
| |
V V
QOpenGLWidget QOpenGLFunctions
So, CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> can be used like any QWidget (which involves making it the main window). It can become as well the center widget of a QMainWindow which gets a menu bar/tool bar with the QAction to open the QFileDialog, request a file path, open a file stream with this file path, and load a mesh from this file stream.
There is another minor detail where I stumbled over: The CGAL::Polyhedron has to be given to the CGAL::SimplePolyhedronViewerQt in the constructor and by const reference. To consider this, it's IMHO necessary (after successful loading of mesh) to construct the CGAL::SimplePolyhedronViewerQt instance by new and set/add it to parent widget afterwards. If this is not acceptable it's probably necessary to go even deeper and replace the CGAL::SimplePolyhedronViewerQt by an own implementation, using the source code of the former as “cheat-sheet”.
This is how such an application could look like:
#include <fstream>
#include <QtWidgets>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
CGAL::DefaultColorFunctorPolyhedron fColor;
Polyhedron mesh;
// setup UI
QMainWindow qWin;
QToolBar qToolbar;
QAction qCmdLoad(QString::fromUtf8("Load File..."));
qToolbar.addAction(&qCmdLoad);
qWin.addToolBar(&qToolbar);
qWin.show();
// install signal handlers
QObject::connect(&qCmdLoad, &QAction::triggered,
[&qWin, &mesh, &fColor]() {
const QString filePath = QFileDialog::getOpenFileName(
&qWin,
QString::fromUtf8("Open .off model"),
QString::fromUtf8("/home"),
QString::fromUtf8("*.off"));
if (filePath.isEmpty()) return;
std::ifstream fIn(filePath.toUtf8().data());
if (!(fIn >> mesh) || mesh.is_empty()) {
qDebug() << "Loading of" << filePath << "failed!";
return;
}
qWin.setCentralWidget(
new CGAL::SimplePolyhedronViewerQt<Polyhedron, CGAL::DefaultColorFunctorPolyhedron>(
&qWin, mesh, "Basic Polyhedron Viewer", false, fColor));
qWin.centralWidget()->show();
});
// runtime loop
return app.exec();
}
Please, take this with a “grain of salt” – I've no CGAL at hand and couldn't compile/test the above code.
CGAL::draw() already handles the Qt stuff. You are trying to open a mainwindow in another one. Just call CGAL::draw(mesh) in your main() function without anything else and it will work.
EDIT: Which is exactly what Sheff explained in a much more detailed way.
I'm trying to do something very simple, I just want to print my native language, pt-br in Windows Console.
IDE Creator
I created a new project->other->Qt Console Application the I put it in my main.cpp file:
#include <QCoreApplication>
#include <QDebug>
#include <QTextCodec>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "aeiou áéíóú";
std::cout << "aeiou áéíóú" << endl;
return 0;
}
here is what I got:
C:\Users\maiko.costa\testeQtConsole\debug>testeQtConsole.exe
aeiou ßÚݾ·
aeiou ßÚݾ·
C:\Users\maiko.costa\testeQtConsole\debug>
I've tried it too, but with the same previous output:
#include <QCoreApplication>
#include <QDebug>
#include <QTextCodec>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextCodec *codec = QTextCodec::codecForName("CP1252");
QTextCodec::setCodecForCStrings(codec);
qDebug() << "aeiou áéíóú";
std::cout << "aeiou áéíóú" << endl;
return 0;
}
The System encode for Windows 7 is it right ?
what am I missing ?
I am not that familiar with QT but I think this can help you just as well. The Windows console uses the OEM char set. Therefore, in order to properly print characters on std::cout they need to be encoded using OEM. This can be accomplished using the Windows API CharToOem.
Small example, just so you get the idea (here input is assumed to be UTF16):
void oemPrint(const wchar_t* str) {
char* chars = (char*)alloca(strlen(str)+1);
CharToOemW(str, chars);
fputs(chars, stdout);
}
// Usage:
oemPrint(L"aeiou áéíóú");
EDIT: A QT solution might be to use QTextCodec::codecForName("IBM 850") - this is the OEM codec.
I find the solution in this thread. Output unicode strings in Windows console app
If I ran chcp 65001 in windows console before I ran my app the characters are printed correctly.
I don't know how to workaround it in my source code, then I call this program manually with the start cpp function.
Here is the return line of function I wrote that displays passwords as ● ● ● ● ●
return QString::fromUtf8( "\u25CF \u25CF \u25CF \u25CF \u25CF" );
QString::fromUnicode should work the same.
Maybe something like:
QString x = QString::fromUtf8( "\u25CF \u25CF \u25CF \u25CF \u25CF" );
std::cout << qPrintable(x) << std::endl;
Of course change it to QString::fromUnicode... hope this helps
QString a="aeiou áéíóú";
std::cout<< a.toStdString().data();
I'm attempting to get readings from a device using the bluetooth Health Device Profile (specifically, an Nonin Onyx II 9560BT). Using this guide, I've been able to do so using python over dbus. Now I'm trying to port it over to C++, and as I'm already using QT in the application, I'm using the QT DBus bindings.
So far I've gotten to the following short program based on this API to test it:
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
if (!QDBusConnection::sessionBus().isConnected()) {
fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n");
return 1;
}
QDBusInterface iface("org.bluez","/org/bluez","org.bluez.HealthManager",QDBusConnection::systemBus(),0);
QVariantMap map;
map.insert("DataType",ushort(1004));//same result with simply 1004
map.insert("Role","Sink");
map.insert("Description","HDP Test Manager"); //Optional
//map.insert("ChannelType","Reliable");//Optional, same result with or without
//QList<QVariant> argumentList;
//argumentList.append(map);
QDBusPendingReply<> r = iface.call("CreateApplication",map);
qDebug() << r.reply();
qDebug() << r.error();
return 0;
}
As far as I can tell, the dict object taken by "CreateApplication" corresponds to an a{sv} which in QT corresponds to the QVariantMap.
However, I keep getting this error:
QDBusMessage(type=Error, service="", error name="org.bluez.Error.InvalidArguments", error message="Invalid arguments in method call", signature="", contents=([]) )
Question: What am I doing wrong?
Based on the guides at freedesktop.org, the qt docs and the mighty google, this is as far as I've gotten.
Thanks for any/all help!
/Keyz182
It works now. It seems that the ushort(0x1004) was getting cast by the QVariant to an int, and thus being picked up as a uint32 by the bluez code, which is not what was expected.
To fix it I did the following (there may be another way, but this worked for me).
I added a Metatype declaration for ushort, then registered it. then, created a QVariant containing the value, and used the QVariants convert method to set the metatype as a ushort (or uint16 when exposed to dbus).
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
Q_DECLARE_METATYPE(ushort); //Added this to declare ushort as a metatype
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
int ushorttype = qDBusRegisterMetaType<ushort>(); //Register the ushort metatype and get it's id
if (!QDBusConnection::sessionBus().isConnected()) {
fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n");
return 1;
}
QDBusInterface iface("org.bluez","/org/bluez","org.bluez.HealthManager",QDBusConnection::systemBus(),0);
QVariant dt(0x1004);
dt.convert((QVariant::Type)ushorttype); //convert to the new type
QVariantMap map;
map.insert("DataType",dt);
map.insert("Role","Sink");
map.insert("Description","HDP Test Manager"); //Optional
QDBusPendingReply<> r = iface.call("CreateApplication",map);
qDebug() << r.isValid();
qDebug() << r.reply();
return 0;
}
I have a Qt GUI application running on Windows that allows command-line options to be passed and under some circumstances I want to output a message to the console and then quit, for example:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (someCommandLineParam)
{
std::cout << "Hello, world!";
return 0;
}
MainWindow w;
w.show();
return a.exec();
}
However, the console messages do not appear when I run the app from a command-prompt. Does anyone know how I can get this to work?
Windows does not really support dual mode applications.
To see console output you need to create a console application
CONFIG += console
However, if you double click on the program to start the GUI mode version then you will get a console window appearing, which is probably not what you want. To prevent the console window appearing you have to create a GUI mode application in which case you get no output in the console.
One idea may be to create a second small application which is a console application and provides the output. This can call the second one to do the work.
Or you could put all the functionality in a DLL then create two versions of the .exe file which have very simple main functions which call into the DLL. One is for the GUI and one is for the console.
Add:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
#endif
at the top of main(). This will enable output to the console only if the program is started in a console, and won't pop up a console window in other situations. If you want to create a console window to display messages when you run the app outside a console you can change the condition to:
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())
void Console()
{
AllocConsole();
FILE *pFileCon = NULL;
pFileCon = freopen("CONOUT$", "w", stdout);
COORD coordInfo;
coordInfo.X = 130;
coordInfo.Y = 9000;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coordInfo);
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),ENABLE_QUICK_EDIT_MODE| ENABLE_EXTENDED_FLAGS);
}
int main(int argc, char *argv[])
{
Console();
std::cout<<"start##";
qDebug()<<"start!";
You can't use std::cout as others have said,my way is perfect even for some code can't include "qdebug" !
So many answers to this topic. 0.0
So I tried it with Qt5.x from Win7 to Win10. It took me some hours to have a good working solution which doesn't produce any problems somewhere in the chain:
#include "mainwindow.h"
#include <QApplication>
#include <windows.h>
#include <stdio.h>
#include <iostream>
//
// Add to project file:
// CONFIG += console
//
int main( int argc, char *argv[] )
{
if( argc < 2 )
{
#if defined( Q_OS_WIN )
::ShowWindow( ::GetConsoleWindow(), SW_HIDE ); //hide console window
#endif
QApplication a( argc, argv );
MainWindow *w = new MainWindow;
w->show();
int e = a.exec();
delete w; //needed to execute deconstructor
exit( e ); //needed to exit the hidden console
return e;
}
else
{
QCoreApplication a( argc, argv );
std::string g;
std::cout << "Enter name: ";
std::cin >> g;
std::cout << "Name is: " << g << std::endl;
exit( 0 );
return a.exec();
}
}
I tried it also without the "CONFIG += console", but then you need to redirect the streams and create the console on your own:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
}
#endif
BUT this only works if you start it through a debugger, otherwise all inputs are directed towards the system too. Means, if you type a name via std::cin the system tries to execute the name as a command. (very strange)
Two other warnings to this attempt would be, that you can't use ::FreeConsole() it won't close it and if you start it through a console the app won't close.
Last there is a Qt help section in QApplication to this topic. I tried the example there with an application and it doesn't work for the GUI, it stucked somewhere in an endless loop and the GUI won't be rendered or it simply crashes:
QCoreApplication* createApplication(int &argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
if (!qstrcmp(argv[i], "-no-gui"))
return new QCoreApplication(argc, argv);
return new QApplication(argc, argv);
}
int main(int argc, char* argv[])
{
QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
if (qobject_cast<QApplication *>(app.data())) {
// start GUI version...
} else {
// start non-GUI version...
}
return app->exec();
}
So if you are using Windows and Qt simply use the console option, hide the console if you need the GUI and close it via exit.
No way to output a message to console when using QT += gui.
fprintf(stderr, ...) also can't print output.
Use QMessageBox instead to show the message.
Oh you can Output a message when using QT += gui and CONFIG += console.
You need printf("foo bar") but cout << "foo bar" doesn't works
Something you may want to investigate, at least for windows, is the AllocConsole() function in the windows api. It calls GetStdHandle a few times to redirect stdout, stderr, etc. (A quick test shows this doesn't entirely do what we want it to do. You do get a console window opened alongside your other Qt stuff, but you can't output to it. Presumably, because the console window is open, there is some way to access it, get a handle to it, or access and manipulate it somehow. Here's the MSDN documentation for those interested in figuring this out:
AllocConsole():
http://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx
GetStdHandle(...):
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx
(I'd add this as a comment, but the rules prevent me from doing so...)
I used this header below for my projects. Hope it helps.
#ifndef __DEBUG__H
#define __DEBUG__H
#include <QtGui>
static void myMessageOutput(bool debug, QtMsgType type, const QString & msg) {
if (!debug) return;
QDateTime dateTime = QDateTime::currentDateTime();
QString dateString = dateTime.toString("yyyy.MM.dd hh:mm:ss:zzz");
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s\n", msg.toAscii().data());
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg.toAscii().data());
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg.toAscii().data());
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg.toAscii().data());
abort();
}
}
#endif
PS: you could add dateString to output if you want in future.
First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...
Second, qDebug is fancy :)
Third, you can try adding console to your .pro's CONFIG, it might work.
In your .pro add
CONFIG += console
It may have been an oversight of other answers, or perhaps it is a requirement of the user to indeed need console output, but the obvious answer to me is to create a secondary window that can be shown or hidden (with a checkbox or button) that shows all messages by appending lines of text to a text box widget and use that as a console?
The benefits of such a solution are:
A simple solution (providing all it displays is a simple log).
The ability to dock the 'console' widget onto the main application window. (In Qt, anyhow).
The ability to create many consoles (if more than 1 thread, etc).
A pretty easy change from local console output to sending log over network to a client.
Hope this gives you food for thought, although I am not in any way yet qualified to postulate on how you should do this, I can imagine it is something very achievable by any one of us with a little searching / reading!
Make sure Qt5Core.dll is in the same directory with your application executable.
I had a similar issue in Qt5 with a console application:
if I start the application from Qt Creator, the output text is visible,
if I open cmd.exe and start the same application there, no output is visible.
Very strange!
I solved it by copying Qt5Core.dll to the directory with the application executable.
Here is my tiny console application:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
int x=343;
QString str("Hello World");
qDebug()<< str << x<<"lalalaa";
QTextStream out(stdout);
out << "aldfjals alsdfajs...";
}
I also played with this, discovering that redirecting output worked, but I never saw output to the console window, which is present for every windows application. This is my solution so far, until I find a Qt replacement for ShowWindow and GetConsoleWindow.
Run this from a command prompt without parameters - get the window. Run from command prompt with parameters (eg. cmd aaa bbb ccc) - you get the text output on the command prompt window - just as you would expect for any Windows console app.
Please excuse the lame example - it represents about 30 minutes of tinkering.
#include "mainwindow.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QApplication>
#include <QWidget>
#include <windows.h>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
if (argc > 1) {
// User has specified command-line arguments
QCoreApplication a(argc, argv);
QTextStream out(stdout);
int i;
ShowWindow (GetConsoleWindow(),SW_NORMAL);
for (i=1; i<argc; i++)
out << i << ':' << argv [i] << endl;
out << endl << "Hello, World" << endl;
out << "Application Directory Path:" << a.applicationDirPath() << endl;
out << "Application File Path:" << a.applicationFilePath() << endl;
MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
return 0;
} else {
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Simple example");
w.show();
return a.exec();
}
}
After a rather long struggle with exactly the same problem I found that simply
CONFIG += console
really does the trick. It won't work until you explicitly tell QtCreator to execute qmake on the project (right click on project) AND change something inside the source file, then rebuild. Otherwise compilation is skipped and you still won't see the output on the command line.
Now my program works in both GUI and cmd line mode.
One solution is to run powershell and redirect the output to whatever stream you want.
Below is an example of running powershell from cmd.exe and redirecting my_exec.exe output to both the console and an output.txt file:
powershell ".\my_exec.exe | tee output.txt"
An example (from cmd.exe) which holds open stdout/stderr and doesn't require tee or a temporary file:
my_exec.exe > NUL 2>&1
Easy
Step1: Create new project. Go File->New File or Project --> Other Project -->Empty Project
Step2: Use the below code.
In .pro file
QT +=widgets
CONFIG += console
TARGET = minimal
SOURCES += \ main.cpp
Step3: Create main.cpp and copy the below code.
#include <QApplication>
#include <QtCore>
using namespace std;
QTextStream in(stdin);
QTextStream out(stdout);
int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
input = in.readLine();
out << "The input is " << input << endl;
return app.exec();
}
I created necessary objects in the code for your understanding.
Just Run It
If you want your program to get multiple inputs with some conditions. Then past the below code in Main.cpp
#include <QApplication>
#include <QtCore>
using namespace std;
QTextStream in(stdin);
QTextStream out(stdout);
int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
do{
input = in.readLine();
if(input.size()==6){
out << "The input is " << input << endl;
}
else
{
qDebug("Not the exact input man");
}
}while(!input.size()==0);
qDebug(" WE ARE AT THE END");
// endif
return app.exec();
} // end main
Hope it educates you.
Good day,
First of all you can try flushing the buffer
std::cout << "Hello, world!"<<std::endl;
For more Qt based logging you can try using qDebug.