Search code examples
c++qtcommand-line-argumentsqcommandlineparser

QCommandLineParser adding functionality to arguments


I'm newbie to Qt Framework and I'm using QCommandLineParser to write a simple console application that could handle some arguments such as :

myapp.exe start

or

myapp.exe get update

How can i understand that user entered an argument ? i want to add functionality to arguments.

here this is my code :

#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;
}

Solution

  • Try checking the size of args. This should help you determine if any of the positional arguments have been specified.
    i.e.

    if(args.size() > 0){
        // do stuff
    }     
    

    And then you can access them like so:

    source = args.at(0);
    dest = args.at(1);
    

    So basically you can check positional args that the user entered like so:

    if((args.size() > 0) && (args.size() == 2)){
       source = args.at(0);
       dest = args.at(1);
    }
    

    To check non-positional args, like your forceOption option, check the value of bool force like so:

    if(force){
        // do stuff since user specified force option
    }