以前使用命令行指定参数启动Qt程序都是用argc和argv,有时用Build环境设置,现在才知道原来Qt从5.2就有了两个类 QCommandLineParser 和 QCommandLineOption ,专门用于命令行启动,它们属于Core模块。
这两个类只在main函数中使用,在使用之前,首先完成两件事:
1. 在pro文件中添加CONFIG += console
,否则不生效。
2. 将exe程序用windeployqt
进行打包。
QCommandLineParser
QCommandLineParser提供了定义一系列命令行参数的功能,储存选项的值。
QCommandLineParser的默认解析模式为ParseAsCompactedShortOptions
,也就是说-abc
会被认为是3个参数,即”-a”、”-b”和”-c”。 当解析模式为ParseAsLongOptions
时,”-abc”会被认为是1个长命令,即”-abc”。
函数addHelpOption()
可以添加程序的帮助信息,这是由Qt自动处理的,用参数-h, --help, ?
触发,这个选项是由QCommandLineParser自动自动处理的。记得用setApplicationDescription
设置程序的描述信息,它会在帮助命令中显示。
类似的,还有函数addVersionOption()
显示程序的版本信息,用-v
触发,也是由Qt自动实现的,记得先用QCoreApplication::setApplicationVersion()
设置版本。
最常用的函数bool QCommandLineParser::addOption(const QCommandLineOption &option)
实际就是上面两个函数的一般化,如果返回TRUE,说明添加成功。
可以用isSet()
判断选项的名称是否被设置。
解析参数可以用 parse(const QStringList &arguments)
方法或 process(const QCoreApplication &app)
方法,前者遇到不可解析的命令会返回false但不会抛出异常,后者则会抛出异常。
optionNames
返回所有选项的名字,用QStringList表示。
通过QCommandLineParser::value
来解析一系列命令行参数
QCommandLineOption
通过QCommandLineOption类定义可能的命令行选项,通过QApplication::arguments()
返回一系列的命令行参数
测试
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName("Application Name");
QCoreApplication::setApplicationVersion("Version: 1");
QCommandLineParser parser;
parser.setApplicationDescription("Description: This is example of console application");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption showCalculation(QStringList() << "o" << "opt", QCoreApplication::translate("main", "Option is: fr") \
,QCoreApplication::translate("main", "opt"), "1");
parser.addOption(showCalculation);
parser.process(a);
const QStringList args = parser.optionNames();
if (args.size() < 1) {
fprintf(stderr, "%s\n", qPrintable(QCoreApplication::translate("main", "Error: Must specify an argument.")));
parser.showHelp(1);
}
QString opt1 = parser.value(showCalculation);
if (opt1 != "fr") {
fprintf(stderr, "%s\n", qPrintable(QCoreApplication::translate
("main", "Error: Invalid format argument. Must be fr")));
parser.showHelp(1);
}
if (opt1 == "fr")
qDebug()<<"Can you see me?";
return 0; //不要再进事件循环
假设exe文件为untitled.exe
,在命令行执行untitled -h
会弹出帮助信息的窗口;untitled -v
弹出版本信息的窗口;untitled.exe -o fr
会在命令行输出can you see me?
,如果不加fr
会报警。