c++qtqtguiqtcoreqapplication

Qt application with optional gui


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

Question is how should be such a program design? Should be some program core, which is GUI independent and depending on options it is being connected with GUI interface?


Solution

  • Yes, you could use a "headless" or "gui" option for the binary using QCommandLineParser. Note that it is only available from 5.3, but the migration path is pretty smooth within the major series if you still do not use that.

    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
    

    Build and Run

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

    Usage

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