如何使用QCommandLineParser处理多参数的参数?

10

我想知道如何在QCommandLineParser中使用多个或子参数?例如:

/home/my_app --my_option_with_two_params first_param second_param --my-option-with-one-param param?
1个回答

13

尝试以下命令,它类似于 -I /my/include/path1 -I /my/include/path2

 --my_option_with_two_params first_param --my_option_with_two_params second_param

...然后您可以使用此方法来访问值:

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

返回给定选项名称optionName找到的选项值列表,如果未找到,则返回空列表。

提供的名称可以是添加了addOption()的任何选项的任何长或短名称。

在这里,您可以找到一个简单的测试用例:

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

构建

qmake && make

使用 --help 时的输出

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>.

运行和输出

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

不要生气:) 我明白你在说什么。我只是不想让我的虚拟用户写 command --option arg1 --option arg2,而是 command --option arg1 arg2。有没有一些内部解决方案,或者我应该为此编写特定的代码? - VALOD9
@VALOD9:自从什么时候你可以在clang中编写包含路径或其他常用软件中使用这种语法?现在,像分隔符这样的东西会很好,这样你就可以写“foo,bar”了,但是只要添加这些内容,复杂性就开始呈指数增长。当我和David Faure一起开发这个类时,我们以最常见的用例为目标,力求简单。几乎不可能为每个人编写通用的解析器,并保持API对大多数人来说简单。 - László Papp
我不是命令行界面的专家:) 我只是查看了Qt 5.2、Qt 5.3和Qt 5.4 beta中的新功能,并尝试理解新特性。所以,你是说在大多数CLI项目中我们没有这样的可能性? - VALOD9
@VALOD9:我的经验表明,在这种情况下使用分隔符是常见的做法,例如在gcc中,但也是非标准的,而且容易引起混淆,因为 -I (包含路径)的工作方式不同,所以它们是不一致的。这个类是为了非常简单,如果需要,可以稍后进行扩展。只是一个快速的问题:你怎么知道 -t foo bar 是仅有 -t foo 和位置参数?但如果你写 -t foo,bar ,你怎么知道 "foo,bar" 是一个字符串还是多个字符串?正如你所看到的,这很容易变得复杂。 - László Papp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接