QCommandLineParser booleans
-
In the details section for
QCommandLineParser
(https://doc.qt.io/qt-5/qcommandlineparser.html#details) the following example is given for C++11 compilers:parser.addOptions({ // A boolean option with a single name (-p) {"p", QCoreApplication::translate("main", "Show progress during copy")}, // A boolean option with multiple names (-f, --force) {{"f", "force"}, QCoreApplication::translate("main", "Overwrite existing files.")}, // An option with a value {{"t", "target-directory"}, QCoreApplication::translate("main", "Copy all source files into <directory>."), QCoreApplication::translate("main", "directory")}, });
However the documentation does not tell you how to check for
p
orf
when using this method. The examples on the page only show you how to check booleans when using aQCommandLineOption
object, but you obviously don't have one handy when using the above syntax.How can this be done?
-
I've never used the class, but it looks like you just check the member function isSet() after running the parse() method.
parser.parse() if (parser.isSet("p")) { /* "-p" was passed */ }
OK...I guess it's process(), not parse()
-
QParser::isSet() also takes a QString.
-
I should have clarified, the
QCommandLineParser::isSet(const QString&)
method uses the option's name, which is not set in the construction I showed. In other words, that doesn't work.In the example above if you try
parser.isSet('p')
it always returns false. -
@Wolosocu said in QCommandLineParser booleans:
parser.isSet('p') i
Did you try
parser.isSet('p')
orparser.isSet("p")
?For me this should work:
int main(int argc, char *argv[]) { // Setting up QCoreApplication QCoreApplication app(argc, argv); // Setting up command line options QCommandLineParser parser; parser.addOptions({ // A boolean option with a single name (-p) {"p", QCoreApplication::translate("main", "Show progress during copy")}, // A boolean option with multiple names (-f, --force) {{"f", "force"}, QCoreApplication::translate("main", "Overwrite existing files.")}, // An option with a value {{"t", "target-directory"}, QCoreApplication::translate("main", "Copy all source files into <directory>."), QCoreApplication::translate("main", "directory")}, }); // Process the actual command line arguments given by the user parser.process(app); if(parser.isSet("p")) { qDebug() << "Found"; } ... }
-
Hi,
parser.isSet('p')
won't build as there's no overload for a char.parser.isSet("p")
works as expected provided you calledparser.process(app);
before checking forp
. -
@Wolosocu said in QCommandLineParser booleans:
method uses the option's name, which is not set in the construction I showed
-
Ah yes.
And of course today, using the
isSet("p");
works even though I swear it wasn't last night. Ah well. Thanks for the answers everyone.