Console output: GUI vs Cmd Line
-
wrote on 3 Mar 2022, 20:57 last edited by
I have a Windows application that can run as a GUI (when no cmd line options are specified) or as a cmd line application (when cmd line options are specified). When running as a cmd line application, I sometimes need to output text. For example, if the user opens a console window and types "app -v", I want to output the application's version. The only way I can get text output seems to be if I put "CONFIG += console" in my .pro file. This would be OK except that when I run as a GUI (by double-clicking the .exe), I get this annoying console popping up as well as my app. I've searched the web about ways to fix this, but have not been able to find an answer. I've tried std::cout, std::cerr, qDebug(), QTextStream (see code below), but all results are the same.
What I would like to have is a GUI that runs without a console window popping up and be able to output text when running as a cmd line application. The code below is a simple example of what I'm trying to do.
QTextStream& qStdOut() { static QTextStream ts( stdout ); return ts; } int main(int argc, char *argv[]) { QApplication a(argc, argv); if (argc > 1) // User included command line arguments { // This only works if "CONFIG += console" is in the .pro file qStdOut() << "Output some text here" << endl; } else // User did not specify command line arguments { // If "CONFIG += console" is in the .pro file, then a // console window also pops up when the main window is // shown (i.e. no cmd line arguments specified) MainWindow w; w.show(); return a.exec(); } }
-
wrote on 5 Mar 2022, 12:11 last edited by khzimmer 3 May 2022, 12:13
Hi,
if you just want to output some simple information you could use QCommandLineParser and its showHelp() method.
Or do it like this:
#include <iostream> //... auto myText = QStringLiteral ("Hello world!"); auto myTranslatedText = QObject::tr ("Hello world!"); std::cout << myText.toUtf8 ().data () << std::endl; std::cout << myTranslatedText.toUtf8 ().data () << std::endl;
-
I think this was just recently discussed at https://forum.qt.io/topic/134576/configure-qapplication-to-work-like-qcoreapplication .
Bottom line: The decision whether a windows executable is attached to a console application or not is a link time decision. There's some ways around this (you can check out e.g. what the Qt Installer Framework does). But the last suggestion in above thread is to just have a .exe and a .cmd entry point for your application, maybe this works for you too?
-
wrote on 7 Mar 2022, 23:12 last edited by
Thank you for your reference to the other forum topic which somehow didn't show up in my search. It looks like they wanted to do the same thing I am trying to do here. I would rather not have to create two applications (one GUI, one cmd line), but not sure if there are any other options at this point.
1/4