QCommandLineParser 学习

QCommandLineParser 是 Qt 用来解析程序启动参数的类。比如运行:

bash 复制代码
.\QCommandLineParserDemo.exe -u -n 2 Alice

程序就能知道:给 Alice 打招呼、名字转成大写、输出两次。

bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe -u -n 2 Alice
Hello, ALICE!
Hello, ALICE!

我已经在当前目录创建了 .pro 示例,并用你本机的 Qt 5.12.12 编译成功 ,验证了正常输出和非法数字处理。

先理解三种参数

类型 示例 如何读取
开关选项 -u 或 --uppercase isSet()
带值选项 -n 2 或 --count 2 value()
位置参数 Alice positionalArguments()

QCommandLineOption 描述某一个选项,QCommandLineParser 负责统一注册、解析和读取这些选项。

pro 文件

cpp 复制代码
QT += core
QT -= gui

TEMPLATE = app
TARGET = QCommandLineParserDemo
CONFIG += console c++11
CONFIG -= app_bundle

SOURCES += main.cpp

这里只需要 Qt Core,console 表示控制台程序。


核心代码怎么理解

创建解析器,并添加帮助、版本选项:

cpp 复制代码
QCommandLineParser parser;
parser.setApplicationDescription("Learn command line parsing with Qt.");
parser.addHelpOption();
parser.addVersionOption();

注册一个开关:

cpp 复制代码
QCommandLineOption upperOption(
    QStringList() << "u" << "uppercase",
    "Print the name in uppercase.");

parser.addOption(upperOption);

这样 -u 和 --uppercase 就是同一个选项的两个名字。

注册一个带值选项:

cpp 复制代码
QCommandLineOption countOption(
    QStringList() << "n" << "count",
    "Number of greetings (1-100).",
    "number",
    "1");

parser.addOption(countOption);

四个参数依次是:选项名称、说明、值的占位名称、默认值 。这里没有传 -n 时,读取到的默认值是 "1"。

bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe Alice
Hello, Alice!
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe A
Hello, A!
bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --uppercase Alice
Hello, ALICE!
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --uppercase Al
Hello, AL!
bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --count 3 Alice
Hello, Alice!
Hello, Alice!
Hello, Alice!
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --count 3 Al
Hello, Al!
Hello, Al!
Hello, Al!
bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --help
Usage: D:\Code\codex\QCommandLineParser\build\release\QCommandLineParserDemo.exe [options] name
Learn command line parsing with Qt.

Options:
  -?, -h, --help        Displays this help.
  -v, --version         Displays version information.
  -u, --uppercase       Print the name in uppercase.
  -n, --count <number>  Number of greetings (1-100).

Arguments:
  name                  Name of the person to greet.
bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --version
QCommandLineParserDemo 1.0
bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe -n abc Alice
Error: --count must be an integer from 1 to 100.

其中 --help 显示帮助,--version 显示版本;-n abc 会触发示例中的数字校验。

学习时记住这个顺序就够了:定义选项 → 添加到解析器 → process() → 读取结果 → 校验并执行业务逻辑。

cpp 复制代码
#include <QCoreApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QTextStream>

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

    // 1. Describe the accepted command line arguments.
    QCommandLineParser parser;
    parser.setApplicationDescription("Learn command line parsing with Qt.");
    parser.addHelpOption();
    parser.addVersionOption();

    // No valueName: a boolean switch, enabled by its presence.
    QCommandLineOption upperOption(QStringList() << "u" << "uppercase",
                                   "Print the name in uppercase.");
    // valueName declares a value; the fourth argument is its default.
    QCommandLineOption countOption(QStringList() << "n" << "count",
                                   "Number of greetings (1-100).", "number", "1");
    parser.addOption(upperOption);
    parser.addOption(countOption);
    // This describes help text; argument count is checked below.
    parser.addPositionalArgument("name", "Name of the person to greet.");

    // 2. Parse arguments, handling --help, --version and syntax errors.
    parser.process(app);

    // 3. Read values and validate application-specific rules.
    QTextStream err(stderr);
    const QStringList args = parser.positionalArguments();
    if (args.size() != 1) {
        err << "Error: provide exactly one name.\n";
        err.flush();
        parser.showHelp(1);
    }

    bool ok = false;
    const int count = parser.value(countOption).toInt(&ok);
    if (!ok || count < 1 || count > 100) {
        err << "Error: --count must be an integer from 1 to 100.\n";
        return 1;
    }

    QString name = args.first();
    if (parser.isSet(upperOption))
        name = name.toUpper();

    QTextStream out(stdout);
    for (int i = 0; i < count; ++i)
        out << "Hello, " << name << "!\n";

    // A one-shot console program needs no app.exec() event loop.
    return 0;
}

修改:

cpp 复制代码
QCoreApplication::setApplicationVersion("1.10");
cpp 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --version
QCommandLineParserDemo 1.10

因为添加了这句:

bash 复制代码
parser.addVersionOption();

所以--version才可以用吧。

注释该行:

bash 复制代码
PS D:\Code\codex\QCommandLineParser\build\release> .\QCommandLineParserDemo.exe --version
Unknown option 'version'.
cpp 复制代码
parser.setApplicationDescription("Learn command line parsing with Qt.我我我");

这句修改的是这里:

bash 复制代码
parser.addHelpOption();

这句决定了有没有 -h这个选项。

bash 复制代码
    QCommandLineOption upperOption(QStringList() << "u" << "uppercase",
                                   "Print the name in uppercase.");

这句话影响的地方:

bash 复制代码
    QCommandLineOption countOption(QStringList() << "n" << "count",
                                   "Number of greetings (1-100).", "number", "1");

这句话影响的地方:

cpp 复制代码
    parser.addOption(upperOption);
    parser.addOption(countOption);

把这两个option添入进去。

cpp 复制代码
parser.addPositionalArgument("name", "Name of the person to greet.");
cpp 复制代码
parser.process(app);

处理参数

cpp 复制代码
QTextStream err(stderr);
const QStringList args = parser.positionalArguments();
if (args.size() != 1) {
    err << "Error: provide exactly one name.\n";
    err.flush();
    parser.showHelp(1);
}  

什么意思

这段代码是在检查:用户是否恰好传入了一个名字 。如果没有,就输出错误、显示帮助并退出程序。

showHelp(1):显示命令行帮助,然后直接退出程序 。1 是退出码,表示运行失败;后面的代码不会继续执行。

cpp 复制代码
    bool ok = false;
    const int count = parser.value(countOption).toInt(&ok);
    if (!ok || count < 1 || count > 100) {
        err << "Error: --count must be an integer from 1 to 100.\n";
        return 1;
    }
cpp 复制代码
    QString name = args.first();
    if (parser.isSet(upperOption))
        name = name.toUpper();
cpp 复制代码
    QTextStream out(stdout);
    for (int i = 0; i < count; ++i)
        out << "Hello, " << name << "!\n";

最后的输出

相关推荐
蒸蒸yyyyzwd33 分钟前
后端学习笔记 day111
笔记·学习
叼烟扛炮1 小时前
[LangChain] 学习笔记(08):工具调用底层闭环与第三方搜索(Tavily)实战
人工智能·笔记·学习·langchain
Century_Dragon2 小时前
让新能源故障诊断实训“触手可及“——仿真教学软件(VR)介绍
学习
楚山之石2 小时前
【Radiology】影像组学的标准化与可重复性:IBSI 卷积滤波器共识及其未能覆盖的环节
人工智能·学习·机器学习·mri
小李不想当小白3 小时前
HAL库之UART(STM32 HAL库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
旖旎夜光4 小时前
【C++ 基础入门】C++ 多态(中):虚函数表、多态原理与动静绑定
开发语言·c++·笔记·学习
旖旎夜光6 小时前
【C++ 基础入门】C++多态(下):单/多继承虚表、多态补充与 21 道高频题
开发语言·c++·笔记·学习
叼烟扛炮11 小时前
[LangChain] 学习笔记(07):大模型长出手脚——工具(Tools)定义与调用闭环
笔记·学习·langchain
叼烟扛炮15 小时前
[LangChain] 学习笔记(06):突破大模型限制——结构化输出(Structured Output)
windows·笔记·学习·langchain
且从容.16 小时前
VUE3学习笔记(根据黑马教程总结)
笔记·学习