我是Qt Framework的新手,我使用QCommandLineParser
编写了一个简单的控制台应用程序,可以处理一些参数,例如:
myapp.exe start
或
myapp.exe get update
我怎么能理解用户输入的参数? 我想为参数添加功能。
这是我的代码:
#include <QCoreApplication>
#include<QTextStream>
#include <QDebug>
#include<QCommandLineParser>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName("Wom");
QCoreApplication::setApplicationVersion("1.0.0");
QCommandLineParser parser;
parser.setApplicationDescription("Test helper");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));
// A boolean option with a single name (-p)
QCommandLineOption showProgressOption("p", QCoreApplication::translate("main", "Show progress during copy"));
parser.addOption(showProgressOption);
// A boolean option with multiple names (-f, --force)
QCommandLineOption forceOption(QStringList() << "f" << "force",
QCoreApplication::translate("main", "Overwrite existing files."));
parser.addOption(forceOption);
// An option with a value
QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory",
QCoreApplication::translate("main", "Copy all source files into <directory>."),
QCoreApplication::translate("main", "directory"));
parser.addOption(targetDirectoryOption);
// Process the actual command line arguments given by the user
parser.process(app);
const QStringList args = parser.positionalArguments();
// source is args.at(0), destination is args.at(1)
bool showProgress = parser.isSet(showProgressOption);
bool force = parser.isSet(forceOption);
QString targetDir = parser.value(targetDirectoryOption);
return 0;
}
答案 0 :(得分:0)
尝试检查args的大小。这应该有助于您确定是否已指定任何位置参数。
即
if(args.size() > 0){
// do stuff
}
然后您可以像这样访问它们:
source = args.at(0);
dest = args.at(1);
因此基本上,您可以像这样检查用户输入的位置参数:
if((args.size() > 0) && (args.size() == 2)){
source = args.at(0);
dest = args.at(1);
}
要检查非位置参数,例如您的forceOption
选项,请像这样检查bool force
的值:
if(force){
// do stuff since user specified force option
}