Qt application with optional gui
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.
You can pass an argument to your application when starting to show in gui or non-gui modes. For example if you pass -non-gui parameter when running in command line then the application should not show the main window and it should do some other stuff :
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();
}