Qt application with optional gui interface

I'm going to write a program using Qt for some image processing, and I want it to be able to work in non-gui mode (daemon mode?). I am inspired by the VLC player, which is a β€œtypically” GUI, where you can configure it using the GUI, but you can also run it in non-gui when it starts without a GUI. Then it uses some configuration file created in GUI mode.

Question: What should be such a program design? There must be some kernel of the program that is independent of the GUI, and depending on the parameters, is it connected with the GUI?

+6
source share
2 answers

Yes, you can use the headless or gui option for binary using QCommandLineParser . Note that it is only available with 5.3, but the migration path is pretty smooth in the main series if you are still not using this.

main.cpp

 #include <QApplication> #include <QLabel> #include <QDebug> #include <QCommandLineParser> #include <QCommandLineOption> int main(int argc, char **argv) { QApplication application(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("My program"); parser.addHelpOption(); parser.addVersionOption(); // A boolean option for running it via GUI (--gui) QCommandLineOption guiOption(QStringList() << "gui", "Running it via GUI."); parser.addOption(guiOption); // Process the actual command line arguments given by the user parser.process(application); QLabel label("Runninig in GUI mode"); if (parser.isSet(guiOption)) label.show(); else qDebug() << "Running in headless mode"; return application.exec(); } 

main.pro

 TEMPLATE = app TARGET = main QT += widgets SOURCES += main.cpp 

Assembly and launch

 qmake && make && ./main qmake && make && ./main --gui 

Using

  Usage: ./main [options] My program Options: -h, --help Displays this help. -v, --version Displays version information. --gui Running it via GUI. 
+9
source

You can pass an argument to your application when you show in gui or non-gui modes. For example, if you pass the -non-gui option at startup on the command line, then the application should not display the main window, and it should do some other things:

 int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; bool GUIMode=true; int num = qApp->argc() ; for ( int i = 0; i < num; i++ ) { QString s = qApp->argv()[i] ; if ( s.startsWith( "-non-gui" ) ) GUIMode = false; } if(GUIMode) { w.show(); } else { //start some non gui functions } return a.exec(); } 
+3
source

Source: https://habr.com/ru/post/969798/


All Articles