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";

最后的输出

相关推荐
minglie12 小时前
幂电枢与幂剩余
学习
优化Henry2 小时前
5G站点AAS-3设备故障排查与处理
运维·学习·5g·信息与通信
andrsted3 小时前
练题簿在线免费刷题:个人备考,从练新题到模拟自测怎么用?
学习·微信小程序·小程序·学习方法·刷题
m0_646429973 小时前
BCrypt 与 JWT 认证流程学习笔记
笔记·学习
apple_692658853 小时前
QX 效率启动器安装包:开源生产力工具,快捷键统一入口Raycast免费开源平替版来啦
学习·开源·办公
一直C4 小时前
嵌入式 Linux 驱动开发学习笔记:中断、等待队列与工作队列
linux·驱动开发·嵌入式硬件·学习·imx6ull
我命由我123454 小时前
5-2.Python 编码进阶 - 字符串进阶(拼接、普通格式化、普通格式化数字精度控制、快速格式化、遍历、常用方法)
java·开发语言·后端·python·学习·java-ee·学习方法
撩得Android一次心动14 小时前
Jetpack Compose 知识点整理2【个人用】
android·笔记·学习·kotlin·compose
dadaobusi15 小时前
学习:灵犀指令集
学习