本页内容

QCommandLineParser Class

QCommandLineParser 类提供了一种处理命令行选项的方法。更多内容...

头文件: #include <QCommandLineParser>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

公共类型

(since 6.9) enum class MessageType { Information, Error }
enum OptionsAfterPositionalArgumentsMode { ParseAsOptions, ParseAsPositionalArguments }
enum SingleDashWordOptionMode { ParseAsCompactedShortOptions, ParseAsLongOptions }

公共函数

QCommandLineParser()
~QCommandLineParser()
QCommandLineOption addHelpOption()
bool addOption(const QCommandLineOption &option)
bool addOptions(const QList<QCommandLineOption> &options)
void addPositionalArgument(const QString &name, const QString &description, const QString &syntax = QString())
QCommandLineOption addVersionOption()
QString applicationDescription() const
void clearPositionalArguments()
QString errorText() const
QString helpText() const
bool isSet(const QString &name) const
bool isSet(const QCommandLineOption &option) const
QStringList optionNames() const
bool parse(const QStringList &arguments)
QStringList positionalArguments() const
void process(const QStringList &arguments)
void process(const QCoreApplication &app)
void setApplicationDescription(const QString &description)
void setOptionsAfterPositionalArgumentsMode(QCommandLineParser::OptionsAfterPositionalArgumentsMode parsingMode)
void setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode)
void showHelp(int exitCode = 0)
void showVersion()
QStringList unknownOptionNames() const
QString value(const QString &optionName) const
QString value(const QCommandLineOption &option) const
QStringList values(const QString &optionName) const
QStringList values(const QCommandLineOption &option) const

静态公共成员

(since 6.9) void showMessageAndExit(QCommandLineParser::MessageType type, const QString &message, int exitCode = 0)

详细说明

QCoreApplication 将命令行参数作为简单的字符串列表提供。QCommandLineParser 提供了定义一组选项、解析命令行参数以及存储实际使用的选项及其值的功能。

任何不是选项的参数(即不以- 开头的参数)都会作为“位置参数”存储。

该解析器支持短名称、长名称、同一选项的多个名称以及选项值。

命令行上的选项被识别为以一个或两个- 字符开头,后跟选项名称。选项- (仅一个连字符)是一个特例,通常表示标准输入,不被视为选项。解析器将选项-- (双连字符)之后的所有内容视为位置参数。

短选项由单个字母组成。选项v 可通过在命令行中输入-v 来指定。在默认解析模式下,短选项可以采用紧凑形式书写,例如-abc 等同于-a -b -c 。解析模式可更改为ParseAsLongOptions ,此时-abc 将被解析为长选项abc 。

长选项由多个字母组成,无法紧凑地组合在一起。长选项verbose 将作为--verbose 或-verbose 传递。

向选项传递值可以使用赋值运算符(-v=value 、--verbose=value ),或使用空格(-v value 、--verbose value )。即使值以- 开头,此方法依然有效。

解析器不支持可选值——如果某个选项被设置为必须提供值,则必须提供该值。如果此类选项位于最后且没有值,则该选项将被视为未指定。

解析器不自动支持通过--disable-option 或--no-option 格式来否定或禁用长选项。不过,可以通过创建一个名称中包含no-option 的选项,并显式处理该选项,来显式处理这种情况。

示例:

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

    QCommandLineParser parser;
    parser.setApplicationDescription("Test helper");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
    parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));

    // A boolean option with a single name (-p)
    QCommandLineOption showProgressOption("p", QCoreApplication::translate("main", "Show progress during copy"));
    parser.addOption(showProgressOption);

    // A boolean option with multiple names (-f, --force)
    QCommandLineOption forceOption(QStringList() << "f" << "force",
            QCoreApplication::translate("main", "Overwrite existing files."));
    parser.addOption(forceOption);

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

    // Process the actual command line arguments given by the user
    parser.process(app);

    const QStringList args = parser.positionalArguments();
    // source is args.at(0), destination is args.at(1)

    bool showProgress = parser.isSet(showProgressOption);
    bool force = parser.isSet(forceOption);
    QString targetDir = parser.value(targetDirectoryOption);
    // ...
}

上例中的三个addOption() 调用可通过使用addOptions() 来简化:

    parser.addOptions({
        // A boolean option with a single name (-p)
        {"p",
            QCoreApplication::translate("main", "Show progress during copy")},
        // A boolean option with multiple names (-f, --force)
        {{"f", "force"},
            QCoreApplication::translate("main", "Overwrite existing files.")},
        // An option with a value
        {{"t", "target-directory"},
            QCoreApplication::translate("main", "Copy all source files into <directory>."),
            QCoreApplication::translate("main", "directory")},
    });

已知限制:QCoreApplication 及其子类内部对Qt选项的解析发生在QCommandLineParser实例创建之前,因此无法将其纳入考虑范围。这意味着任何看起来像Qt内置选项的选项值,都会被QCoreApplication 视为Qt内置选项。 示例:--profile -reverse 将导致QGuiApplication 检测到已设置的-reverse选项,并在QCommandLineParser定义profile 选项并解析命令行之前,将其从QCoreApplication::arguments()中移除。

如何在复杂应用程序中使用 QCommandLineParser

实际上,需要对位置参数和选项值进行额外的错误检查。例如,应检查数字范围。

因此,建议引入一个用于解析命令行的函数,该函数接受一个用于接收选项值的结构体或类,并返回一个表示解析结果的对象。QtNetwork 模块中的dnslookup示例说明了这一点:

struct DnsQuery
{
    DnsQuery() : type(QDnsLookup::A) {}

    QDnsLookup::Type type;
    QHostAddress nameServer;
    QString name;
};

struct CommandLineParseResult
{
    enum class Status {
        Ok,
        Error,
        VersionRequested,
        HelpRequested
    };
    Status statusCode = Status::Ok;
    std::optional<QString> errorString = std::nullopt;
};

CommandLineParseResult parseCommandLine(QCommandLineParser &parser, DnsQuery *query)
{
    using Status = CommandLineParseResult::Status;

    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
    const QCommandLineOption nameServerOption("n", "The name server to use.", "nameserver");
    parser.addOption(nameServerOption);
    const QCommandLineOption typeOption("t", "The lookup type.", "type");
    parser.addOption(typeOption);
    parser.addPositionalArgument("name", "The name to look up.");
    const QCommandLineOption helpOption = parser.addHelpOption();
    const QCommandLineOption versionOption = parser.addVersionOption();

    if (!parser.parse(QCoreApplication::arguments()))
        return { Status::Error, parser.errorText() };

    if (parser.isSet(versionOption))
        return { Status::VersionRequested };

    if (parser.isSet(helpOption))
        return { Status::HelpRequested };

    if (parser.isSet(nameServerOption)) {
        const QString nameserver = parser.value(nameServerOption);
        query->nameServer = QHostAddress(nameserver);
        if (query->nameServer.isNull()
            || query->nameServer.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
            return { Status::Error,
                     u"Bad nameserver address: %1"_s.arg(nameserver) };
        }
    }

    if (parser.isSet(typeOption)) {
        const QString typeParameter = parser.value(typeOption);
        if (std::optional<QDnsLookup::Type> type = typeFromParameter(typeParameter))
            query->type = *type;
        else
            return { Status::Error, u"Bad record type: %1"_s.arg(typeParameter) };
    }

    const QStringList positionalArguments = parser.positionalArguments();
    if (positionalArguments.isEmpty())
        return { Status::Error, u"Argument 'name' missing."_s };
    if (positionalArguments.size() > 1)
        return { Status::Error, u"Several 'name' arguments specified."_s };
    query->name = positionalArguments.first();

    return { Status::Ok };
}

在 main 函数中,如果传入了 help 选项,应将帮助信息打印到标准输出,并且应用程序应返回退出代码 0。

如果检测到错误,应将错误消息输出到标准错误输出,并且应用程序应返回非 0 的退出代码。

    QCoreApplication::setApplicationVersion(QT_VERSION_STR);
    QCoreApplication::setApplicationName(QCoreApplication::translate("QDnsLookupExample",
                                                                     "DNS Lookup Example"));
    QCommandLineParser parser;
    parser.setApplicationDescription(QCoreApplication::translate("QDnsLookupExample",
                                                                 "An example demonstrating the "
                                                                 "class QDnsLookup."));
    DnsQuery query;
    using Status = CommandLineParseResult::Status;
    CommandLineParseResult parseResult = parseCommandLine(parser, &query);
    switch (parseResult.statusCode) {
    case Status::Ok:
        break;
    case Status::Error:
        std::fputs(qPrintable(parseResult.errorString.value_or(u"Unknown error occurred"_s)),
                   stderr);
        std::fputs("\n\n", stderr);
        std::fputs(qPrintable(parser.helpText()), stderr);
        return 1;
    case Status::VersionRequested:
        parser.showVersion();
        Q_UNREACHABLE_RETURN(0);
    case Status::HelpRequested:
        parser.showHelp();
        Q_UNREACHABLE_RETURN(0);
    }

这里需要考虑的一个特例是 Windows 和移动平台上的图形用户界面(GUI)应用程序。由于这些应用程序的输出要么被丢弃,要么无法访问,因此可能不会使用标准输出或错误通道。

在 Windows 系统上,若无法获取控制台窗口,QCommandLineParser 将使用消息框来显示用法信息和错误。通过设置环境变量 `QT_COMMAND_LINE_PARSER_NO_GUI_MESSAGE_BOXES `,可以省略这些消息框。

对于其他平台,建议使用QMessageBox 显示帮助文本和错误消息。为保留帮助文本的格式,应使用包含<pre> 元素的富文本:

switch (parseResult.statusCode) {
case Status::Ok:
    break;
case Status::Error: {
    QString errorMessage = parseResult.errorString.value_or(u"Unknown error occurred"_qs);
    QMessageBox::warning(0, QGuiApplication::applicationDisplayName(),
                         "<html><head/><body><h2>" + errorMessage + "</h2><pre>"
                         + parser.helpText() + "</pre></body></html>");
    return 1;
}
case Status::VersionRequested:
    QMessageBox::information(0, QGuiApplication::applicationDisplayName(),
                             QGuiApplication::applicationDisplayName() + ' '
                             + QCoreApplication::applicationVersion());
    return 0;
case Status::HelpRequested:
    QMessageBox::warning(0, QGuiApplication::applicationDisplayName(),
                         "<html><head/><body><pre>"
                         + parser.helpText() + "</pre></body></html>");
    return 0;
}

不过,这并不适用于 dnslookup 示例,因为它是一个控制台应用程序。

另请参阅 QCommandLineOption 和QCoreApplication 。

成员类型文档

[since 6.9] enum class QCommandLineParser::MessageType

该枚举用于指定消息的类型以及向用户显示的方式。

常量值描述
QCommandLineParser::MessageType::Information0用于显示信息消息。该消息将输出到stdout 。
QCommandLineParser::MessageType::Error1用于显示错误消息。该消息将输出到stderr 。

该枚举在 Qt 6.9 中引入。

另请参阅 showMessageAndExit()。

enum QCommandLineParser::OptionsAfterPositionalArgumentsMode

此枚举描述了解析器如何解释位于位置参数之后的选项。

常量值描述
QCommandLineParser::ParseAsOptions0application argument --opt -t 将被解释为设置选项opt 和t ,就像application --opt -t argument 所做的那样。这是默认的解析模式。为了指定--opt 和-t 实际上是位置参数,用户可以使用-- ,例如application argument -- --opt -t 。
QCommandLineParser::ParseAsPositionalArguments1application argument --opt 将被解释为包含两个位置参数:argument 和--opt 。 此模式对于旨在启动其他可执行文件(例如包装器、调试工具等)或支持内部命令(后跟该命令的选项)的可执行文件非常有用。argument 是命令的名称,其后出现的所有选项均可由另一个命令行解析器(可能位于另一个可执行文件中)收集并解析。

另请参阅 setOptionsAfterPositionalArgumentsMode()。

enum QCommandLineParser::SingleDashWordOptionMode

此枚举描述了解析器如何解释以单个连字符开头、后跟多个字母的命令行选项,例如-abc 。

常量值描述
QCommandLineParser::ParseAsCompactedShortOptions0-abc 将被解释为-a -b -c ,即三个在命令行上被压缩的简短选项,前提是这些选项均未带值。 如果a 取值,则将其解释为-a bc ,即短选项a 后面跟值bc 。这通常用于类似编译器的工具中,以处理诸如-DDEFINE=VALUE 或-I/include/path 之类的选项。这是默认的解析模式。建议新应用程序使用此模式。
QCommandLineParser::ParseAsLongOptions1-abc 将被解释为--abc ,即名为abc 的长选项。这是 Qt 自身工具(如 uic、rcc 等)一直以来解析参数的方式。对于采用此类解析方式的应用程序,应使用此模式以保持兼容性。 若a 选项设置了QCommandLineOption::ShortOptionStyle 标志,则存在例外情况,此时该参数仍被解释为-a bc 。

另请参阅 setSingleDashWordOptionMode()。

成员函数文档

QCommandLineParser::QCommandLineParser()

构建一个命令行解析器对象。

[noexcept] QCommandLineParser::~QCommandLineParser()

销毁命令行解析器对象。

QCommandLineOption QCommandLineParser::addHelpOption()

为命令行解析器添加帮助选项。

此命令行的选项说明请参见-h 或--help 。在 Windows 系统上,还支持-? 这一替代链接。选项--help-all 可将输出范围扩展至包含未由该命令定义的通用 Qt 选项。

这些选项由QCommandLineParser 自动处理。

请记住使用setApplicationDescription() 来设置应用程序描述,该描述将在使用此选项时显示。

示例:

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

    QCommandLineParser parser;
    parser.setApplicationDescription("Test helper");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
    parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));

    // A boolean option with a single name (-p)
    QCommandLineOption showProgressOption("p", QCoreApplication::translate("main", "Show progress during copy"));
    parser.addOption(showProgressOption);

    // A boolean option with multiple names (-f, --force)
    QCommandLineOption forceOption(QStringList() << "f" << "force",
            QCoreApplication::translate("main", "Overwrite existing files."));
    parser.addOption(forceOption);

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

    // Process the actual command line arguments given by the user
    parser.process(app);

    const QStringList args = parser.positionalArguments();
    // source is args.at(0), destination is args.at(1)

    bool showProgress = parser.isSet(showProgressOption);
    bool force = parser.isSet(forceOption);
    QString targetDir = parser.value(targetDirectoryOption);
    // ...
}

返回选项实例,可用于调用isSet()。

bool QCommandLineParser::addOption(const QCommandLineOption &option)

在解析时添加要查找的选项option 。

若添加选项成功,则返回true ;否则返回false 。

如果选项未指定名称,或者该选项的名称与先前添加的选项名称冲突,则添加该选项将失败。

bool QCommandLineParser::addOptions(const QList<QCommandLineOption> &options)

添加在解析过程中需要查找的选项。这些选项由参数options 指定。

如果所有选项均添加成功,则返回 `true `;否则返回 `false`。

有关此函数可能失败的情况,请参阅addOption() 的文档。

void QCommandLineParser::addPositionalArgument(const QString &name, const QString &description, const QString &syntax = QString())

为应用程序定义一个额外参数,以便在帮助文本中使用。

参数name 和description 将显示在帮助文档的“Arguments: ”部分下。如果指定了syntax ,该参数将被追加到“Usage”行中;否则,将追加name 。

示例:

// Usage: image-editor file
//
// Arguments:
//   file                  The file to open.
parser.addPositionalArgument("file", QCoreApplication::translate("main", "The file to open."));

// Usage: web-browser [urls...]
//
// Arguments:
//   urls                URLs to open, optionally.
parser.addPositionalArgument("urls", QCoreApplication::translate("main", "URLs to open, optionally."), "[urls...]");

// Usage: cp source destination
//
// Arguments:
//   source                Source file to copy.
//   destination           Destination directory.
parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));

另请参阅 addHelpOption() 和helpText()。

QCommandLineOption QCommandLineParser::addVersionOption()

添加了-v /--version 选项,该选项会显示应用程序的版本字符串。

该选项由QCommandLineParser 自动处理。

您可以通过调用QCoreApplication::setApplicationVersion() 来设置实际的版本字符串。

返回该选项实例,可用于调用isSet()。

QString QCommandLineParser::applicationDescription() const

返回在setApplicationDescription() 中设置的应用程序描述。

另请参阅 setApplicationDescription()。

void QCommandLineParser::clearPositionalArguments()

从帮助文本中清除附加参数的定义。

这仅适用于支持带有不同选项的多个命令的工具这一特殊情况。一旦确定了实际的命令,即可定义该命令的选项,并相应地调整该命令的帮助文本。

示例:

QCoreApplication app(argc, argv);
QCommandLineParser parser;

parser.addPositionalArgument("command", "The command to execute.");

// Call parse() to find out the positional arguments.
parser.parse(QCoreApplication::arguments());

const QStringList args = parser.positionalArguments();
const QString command = args.isEmpty() ? QString() : args.first();
if (command == "resize") {
    parser.clearPositionalArguments();
    parser.addPositionalArgument("resize", "Resize the object to a new size.", "resize [resize_options]");
    parser.addOption(QCommandLineOption("size", "New size.", "new_size"));
    parser.process(app);
    // ...
}

/*
This code results in context-dependent help:

$ tool --help
Usage: tool command

Arguments:
  command  The command to execute.

$ tool resize --help
Usage: tool resize [resize_options]

Options:
  --size <size>  New size.

Arguments:
  resize         Resize the object to a new size.
*/

QString QCommandLineParser::errorText() const

返回给用户的翻译后的错误文本。仅当parse()返回false 时,才应调用此函数。

QString QCommandLineParser::helpText() const

返回一个包含完整帮助信息的字符串。

另请参阅 showHelp()。

bool QCommandLineParser::isSet(const QString &name) const

检查是否向应用程序传递了name 选项。

如果已设置选项 `name `,则返回 `true `;否则返回 `false`。

提供的名称可以是任何通过addOption() 添加的选项的任意长名称或短名称。所有选项名称均被视为等效。如果名称无法识别或该选项不存在,则返回 false。

示例:

bool verbose = parser.isSet("verbose");

bool QCommandLineParser::isSet(const QCommandLineOption &option) const

检查option 是否已传递给应用程序。

如果已设置option ,则返回true ;否则返回false。

这是检查无值选项的推荐方法。

示例:

QCoreApplication app(argc, argv);
QCommandLineParser parser;
QCommandLineOption verboseOption("verbose");
parser.addOption(verboseOption);
parser.process(app);
bool verbose = parser.isSet(verboseOption);

这是一个重载函数。

QStringList QCommandLineParser::optionNames() const

返回所找到的选项名称列表。

该函数返回解析器识别出的所有选项名称的列表,按发现的顺序排列。对于任何采用 {–option=value} 形式的冗长选项,其值部分将被省略。

该列表中的名称不包含前面的连字符。如果解析器遇到某个选项名称多次,该名称可能会在列表中出现多次。

列表中的任何条目均可与 `value()` 或 `values()` 配合使用,以获取相关的选项值。

bool QCommandLineParser::parse(const QStringList &arguments)

解析命令行arguments 。

大多数程序无需调用此函数,只需简单调用process() 即可。

parse() 属于更底层的函数,仅负责解析。如果 parse() 返回false ,应用程序必须通过调用errorText() 来处理错误。例如,这在图形化程序中显示图形化错误消息时会很有用。

在调用process() 之前,通过使用 parse() 代替process() 暂时忽略未知选项也是有用的,因为稍后(取决于某个参数)将提供更多的选项定义。

请注意,arguments 必须以可执行文件名开头(尽管该部分会被忽略)。

如果发生解析错误(未知选项或缺少值),则返回false ;否则返回true 。

另请参阅 process()。

QStringList QCommandLineParser::positionalArguments() const

返回一个位置参数列表。

这些是所有未被识别为选项组成部分的参数。

void QCommandLineParser::process(const QStringList &arguments)

处理命令行arguments 。

除了解析选项(如parse())外,该函数还处理内置选项并处理错误。

内置选项包括:如果调用了 `addVersionOption `,则为 `--version `;如果调用了 `addHelpOption `,则为 `--help ` 或 `--help-all `。

当调用这些选项之一时,或者发生错误时(例如传入了未知选项),当前进程将通过 exit() 函数终止。

另请参阅 QCoreApplication::arguments() 和parse()。

void QCommandLineParser::process(const QCoreApplication &app)

该命令行是从QCoreApplication 实例app 中获取的。

这是一个重载函数。

void QCommandLineParser::setApplicationDescription(const QString &description)

设置由helpText() 显示的应用程序description 。

另请参阅 applicationDescription()。

void QCommandLineParser::setOptionsAfterPositionalArgumentsMode(QCommandLineParser::OptionsAfterPositionalArgumentsMode parsingMode)

将解析模式设置为parsingMode 。必须在调用process()或parse()之前调用此函数。

void QCommandLineParser::setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode)

将解析模式设置为singleDashWordOptionMode 。必须在调用process()或parse()之前调用此函数。

void QCommandLineParser::showHelp(int exitCode = 0)

显示帮助信息,并退出应用程序。此操作会由 –help 选项自动触发,但也可在用户未正确调用应用程序时用于显示帮助。 退出代码设置为exitCode 。如果用户请求查看帮助,则应将其设置为0;若发生错误,则应设置为其他任意值。

另请参阅 helpText() 和showMessageAndExit()。

[static, since 6.9] void QCommandLineParser::showMessageAndExit(QCommandLineParser::MessageType type, const QString &message, int exitCode = 0)

显示message ,并使用给定的exitCode 退出应用程序。

该message 通常会根据给定的type 直接打印到stdout 或stderr 上;或者,在必要时,该消息可能会在Windows下显示在消息框中,并根据给定的type 显示信息图标或错误图标(如果您不想显示消息框,请设置QT_COMMAND_LINE_PARSER_NO_GUI_MESSAGE_BOXES 环境变量)。

这与showHelp 、showVersion 以及内置选项(若调用addVersionOption 则为--version ,若调用addHelpOption 则为--help /--help-all )所使用的消息显示方式相同。

该函数在 Qt 6.9 中引入。

另请参阅 addVersionOption()、showHelp()、showVersion() 以及QCommandLineParser::MessageType 。

void QCommandLineParser::showVersion()

显示来自QCoreApplication::applicationVersion() 的版本信息,并退出应用程序。此操作会由 –version 选项自动触发,但在未使用process() 时,也可用于显示版本信息。退出代码设置为 EXIT_SUCCESS (0)。

另请参阅 addVersionOption()。

QStringList QCommandLineParser::unknownOptionNames() const

返回一个未知选项名称的列表。

该列表将包含所有未被识别的长选项和短选项。对于任何形式为 {–option=value} 的长选项,其值部分将被省略,仅添加长选项名称。

该列表中的名称不包含前面的连字符。如果解析器遇到某个选项名称多次,该名称可能会在列表中出现多次。

另请参阅 optionNames()。

QString QCommandLineParser::value(const QString &optionName) const

返回为给定选项名称 `optionName` 找到的选项值;若未找到,则返回空字符串。

提供的名称可以是任何通过 `addOption()` 添加的选项的任一长名称或短名称。所有选项名称均被视为等效。如果名称无法识别或该选项不存在,则返回空字符串。

对于解析器找到的选项,将返回该选项的最后一个已知值。如果该选项未在命令行中指定,则返回默认值。

如果该选项不接受值,则会输出警告,并返回空字符串。

另请参阅 values()、QCommandLineOption::setDefaultValue() 和QCommandLineOption::setDefaultValues()。

QString QCommandLineParser::value(const QCommandLineOption &option) const

返回为给定的option 找到的选项值;如果未找到,则返回空字符串。

对于解析器找到的选项,将返回该选项的最后一个已知值。如果该选项未在命令行中指定,则返回其默认值。

如果该选项不接受值,则返回空字符串。

这是一个重载函数。

另请参阅 values()、QCommandLineOption::setDefaultValue() 和QCommandLineOption::setDefaultValues()。

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

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

提供的名称可以是任何通过addOption() 添加的选项的完整名称或简写名称。所有选项名称均被视为等效。如果名称无法识别或该选项不存在,则返回一个空列表。

对于解析器找到的选项,该列表将包含解析器每次遇到该选项时对应的一条条目。如果该选项未在命令行中指定,则返回其默认值。

如果选项不接受值,则返回一个空列表。

另请参阅 value()、QCommandLineOption::setDefaultValue() 和QCommandLineOption::setDefaultValues()。

QStringList QCommandLineParser::values(const QCommandLineOption &option) const

返回针对给定的option 所找到的选项值列表;若未找到,则返回空列表。

对于解析器检测到的选项,该列表将包含解析器每次遇到该选项时对应的一条记录。如果该选项未在命令行中指定,则返回其默认值。

如果该选项不接受值,则返回一个空列表。

这是一个重载函数。

另请参阅 value()、QCommandLineOption::setDefaultValue() 和QCommandLineOption::setDefaultValues()。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.