QCommandLineParser:向参数添加功能

3

我是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;
}
1个回答

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接