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

最后的输出

相关推荐
鱼很腾apoc1 天前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习
楚山之石2 天前
【Lancet】BRAID 随机试验:乳腺致密女性补充成像,abbreviated MRI 与 CEM 检出更多早期癌(首轮中期结果)
人工智能·科技·学习·mri·医学影像
Sunflower_ac2 天前
强化学习学习笔记:Lab 0–Lab 2
笔记·学习
Z21-X2 天前
云原生运维学习笔记:Kubernetes 自动扩缩容与资源管控实战
运维·笔记·学习·云原生·kubernetes
可涵不会debug2 天前
ChatServer 模块学习笔记:HTTP 接入层、多线程与流式响应
笔记·学习·http
console.log('npc')3 天前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
艾莉丝努力练剑3 天前
【AI大模型接入SDK】解决Unicode码转化以及界面变形问题
前端·c++·人工智能·学习·安全·架构
旖旎夜光3 天前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
大连好光景3 天前
腾讯云 ADP 前沿部署工程师 (FDE) 学习笔记(二)
笔记·学习·agent开发平台·adp·实战练习
IT空门:门主4 天前
LangChain4j 1.24.0 深度解读:新特性、版本对比与学习路线
java·学习