0

I was looking on how to parse the command line arguments. I found this:

// A boolean option with multiple names (-f, --force)
QCommandLineOption forceOption(QStringList() << "f" << "force",
        QCoreApplication::translate("main", "Overwrite existing files."));
parser.addOption(forceOption);

This works fine. But how can I add two values for a string value? For example, foo --source ... should be the same with foo -s ....

I tried:

parser.addPositionalArgument(
   QStringList() << "s" << "source",
   QCoreApplication::translate("main", "...")
);

But this throws an error:

error: no matching function for call to 
'QCommandLineParser::addPositionalArgument(QStringList&, QString)'
parser.addPositionalArgument(QStringList() << "t" << "title",
QCoreApplication::translate("main", "...."));

That's probably addPositionalArgument expects a string instead of a string list.

But how can I alias two values?

msrd0
  • 7,816
  • 9
  • 47
  • 82
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

1

You don't use a positional argument for that. Positional arguments are arguments that need to appear in a specific order, and can have any value. They are no parameters introduced with something like -s or --source.

As you already found out, you can alias the two using a QStringList in QCommandLineOption. If you want an argument to follow, just specify this in the constructor:

QCommandLineOption sourceOption(
    QStringList() << "s" << "source",
    "Specify the source", // better translate that string
    "source", // the name of the following argument
    "something" // the default value of the following argument, not required
);
parser.addOption(sourceOption);
msrd0
  • 7,816
  • 9
  • 47
  • 82
  • And how can I differentiate between string and boolean? – Ionică Bizău Dec 23 '14 at 11:05
  • @IonicăBizău You get a [`QVariant`](http://qt-project.org/doc/qt-4.8/qvariant.html) when accesing the argument so you can call `toBool` to get a boolean and `toString` to get a string. `type()` will return whether this is a bool or a string – msrd0 Dec 23 '14 at 11:12
  • I guess then I have to call `parser.addOption(sourceOption);`, right? – Ionică Bizău Dec 23 '14 at 12:21
  • @IonicăBizău Yes, that need to be added after my code snippet – msrd0 Dec 23 '14 at 12:45