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";
最后的输出