How to use QCommandLineParser for arguments with multiple params?

那年仲夏 提交于 2019-12-22 04:58:41

问题


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?

回答1:


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 and Run

qmake && make

Run and Output

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


来源:https://stackoverflow.com/questions/26590362/how-to-use-qcommandlineparser-for-arguments-with-multiple-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!