Using QCommandLineParser with QGuiApplication
-
I am trying to add a CLI to my existing GUI application, but whenever I use, for example,
--versiona dialog window opens up instead of writing the text in terminal. Here is the main code:#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QCommandLineParser> #include <iostream> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); #ifdef APP_VERSION QCoreApplication::setApplicationVersion(QString(APP_VERSION)); #else QCoreApplication::setApplicationVersion(QString("dev")); #endif QCoreApplication::setApplicationName(QCoreApplication::translate("gav", "GAV is a simple audio and video player, backed by FFmpeg and Qt6")); QCommandLineParser parser; parser.setApplicationDescription("GAV is a simple audio and video player, backed by FFmpeg and Qt6"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption sourceOption("source", "Source of the audio or video to play"); parser.addOption(sourceOption); parser.process(app); QString sourceValue; if (parser.isSet(sourceOption)) { sourceValue = parser.value(sourceOption); } QQmlApplicationEngine engine; if (!sourceValue.isEmpty()) { QUrl sourceURL = QUrl::fromUserInput(sourceValue); if (!sourceURL.isEmpty() && sourceURL.isValid()) engine.setInitialProperties({{"source", sourceURL}}); } QObject::connect( &engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() { QCoreApplication::exit(-1); }, Qt::QueuedConnection); if (!parser.isSet("version") || !parser.isSet("help")) { engine.loadFromModule("gavqml", "Main"); } return app.exec(); }I tried to do this:
if (!parser.isSet("version") || !parser.isSet("help")) { engine.loadFromModule("gavqml", "Main"); }So that the engine doesn't load the qml, but the dialog still shows up.
What is the correct way of doing this?
-
It will always pop a message box if your application doesn't have an attached console, which is the normal case when running a gui application on Windows, even started from console.
(From Qt's internal source code, the message box could be avoid by setting enviroment variable "QT_COMMAND_LINE_PARSER_NO_GUI_MESSAGE_BOXES" but still there won't be text written to console since none is attached.)
You need to configure your project to be a console application so that it will automatically attach the console, but this will bring a new problem: when running the applicaion by double clicking, it will also open a console window (with GUI window). In order to solve that you'll need to find a way to know it is started from console or not, if not, close the console. That's a little complicated, normally windows GUI applications just don't have CLI for console/terminal.
If you are interested, here is how Qt installer checks whether started from console or not:
https://github.com/qtproject/installer-framework/blob/master/src/sdk/main.cpp#L352 -
That's really helpful. thank you.
-
A akshaybabloo has marked this topic as solved on