I have a console application using QCoreApplication in Qt5. This application has different functions like "printABC" or "printSUV". The output will appear in the terminal. Now I want to make a Gui, where I can push the buttons "printABC" or "printSUV" and the output will appear in the terminal too, so that it is 'easier' to use the application. In Qt5, I can make a console application using QCoreApplication, which I have already done. So my question is how can I add a QApplication which runs along the way? In the docs, it is recommended to create a QApplication/QCoreApplication in the main function, so how can I create both?
You can easily have a single application which supports both command-line (terminal) mode and GUI mode. Just use QApplication
(or QGuiApplication
for QML-only app).
UPDATE 1: The commenters are correct, it would be better to instantiate QCoreApplication
or Q[Gui]Application
depending on which is actually needed...
Then, for example, if a user passes CLI options, you just run the function(s) and send the result to sdtout
(presumably like you're doing now). Otherwise show the GUI and use the same functions but to display the data some other way (in the UI).
UPDATE 2: ... So it would be better to parse the command line first and determine which Q*Application "flavor" should be used...
If you haven't yet, you can look into QCommandLineParser to help handle the CLI options. Just keep in mind that it works exactly the same with a Q[Gui]Application
as well.
UPDATE 3: ... In fact QCommandLineParser
can be used before a Q*Application
is created. One just needs to call parse()
with a list of options from argv
, instead of process()
with the app instance. See code example below.
In main()
, handle any CLI options first. Then to NOT launch the GUI you could simply exit(0)
from main()
before calling app.exec()
.
A basic example:
int main(int argc, char *argv[]) {
QCoreApplication *app;
QCommandLineParser clp;
clp.setApplicationDescription("My app does great things.");
clp.addOptions({{"cli", "Use CLI interface"}});
QStringList opts;
for (int i=0; i < argc; ++i)
opts << QString(argv[i]);
clp.parse(opts);
if (clp.isSet("cli"))
app = new QCoreApplication(argc, argv);
else
app = new QApplication(argc, argv);
...
return app->exec(); // or maybe just 0, or app->exit(), if no event loop is needed.
}
If you want to show the output in the console from which the application was started, then you can still simply print to stdout
(or whatever you're doing now). However if you want this to work on Windows, additional steps may be required... and there are a few things to consider. This would really be the topic of a different question, I think. IMHO mixing the two (GUI in one window and output in console) could be rather awkward, and showing output in GUI makes it all nicely self-contained.