Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console output in a Qt GUI app?

Tags:

c++

windows

qt

qt4

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?

like image 959
Rob Avatar asked Jul 29 '10 08:07

Rob


People also ask

Is QT a GUI?

Qt is a cross-platform application and graphical user interface (GUI) framework, a toolkit, that is used for developing software that can be run on different hardware platforms and operating systems.


2 Answers

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.

like image 126
David Dibben Avatar answered Sep 27 '22 22:09

David Dibben


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()) 
like image 21
patstew Avatar answered Sep 27 '22 20:09

patstew