QCommandLineParser为参数添加功能

时间:2017-04-13 19:21:06

标签: c++ qt command-line-arguments command-line-parsing qcommandlineparser

我是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 :(得分: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
}