How to use QCommandLineParser for arguments with multiple params?

VALOD9 picture VALOD9 · Oct 27, 2014 · Viewed 12.6k times · Source

I wonder, how can I use multiple- or sub-arguments with QCommandLineParser? For example:

/home/my_app --my_option_with_two_params first_param second_param --my-option-with-one-param param?

Answer

lpapp picture lpapp · Oct 27, 2014

Try this which has the analogy of -I /my/include/path1 -I /my/include/path2:

 --my_option_with_two_params first_param --my_option_with_two_params second_param

... and then you can use this method to have access to the values:

QStringList QCommandLineParser::values(const QString & optionName) const

Returns a list of option values found for the given option name optionName, or an empty list if not found.

The name provided can be any long or short name of any option that was added with addOption().

Here you can find a simple test case that works:

main.cpp

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("multiple-values-program");
    QCoreApplication::setApplicationVersion("1.0");

    QCommandLineParser parser;
    parser.setApplicationDescription("Test helper");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory",
            QCoreApplication::translate("main", "Copy all source files into <directory>."),
            QCoreApplication::translate("main", "directory"));
    parser.addOption(targetDirectoryOption);

    parser.process(app);

    qDebug() << parser.values(targetDirectoryOption);
    return 0;
}

main.pro

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

Build

qmake && make

Output when --help is used

Usage: main [options]
Test helper

Options:
  -h, --help                          Displays this help.
  -v, --version                       Displays version information.
  -t, --target-directory <directory>  Copy all source files into <directory>.

Run and Output

./main -t foo -t bar -> ("foo", "bar")
./main -t foo bar    -> ("foo")