1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the tools applications of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 #include <QTextBoundaryFinder>
44 #include <QCoreApplication>
47 #include <QStringList>
48 #include <QTextStream>
51 #include "qapplicationargument_p.h"
53 #include "qapplicationargumentparser_p.h"
58 \class QApplicationArgumentParser
59 \brief The QApplicationArgumentParser class parses the command
60 line arguments for an application.
65 QApplicationArgumentParser simplifies writing command line applications by taking care of:
68 \li Generating help and version arguments
69 \li Taking care of converting arguments to QVariant types, since each argument
70 has a type: QApplicationArgument::type()
71 \li Validates the command line such that the user operates on well-defined input. For instance,
72 that the argument is a valid integer if that is the case, that an argument does not
73 occur more times than allowed, and so on.
74 \li Allows customization through sub-classing.
77 The user declares what arguments that can be given to the application with QApplicationArgument. Provided
78 with that information, QApplicationArgumentParser takes care of parsing the actual
79 command line, appropriately flag errors, generate help messages, and provide
80 convenient access to the values of the arguments.
82 The way to use it is to create a set of QApplicationArgument by ones choosing, call
83 addArgument() for each, and subsequently call parse(). If parse() returns \c false,
84 the caller should exit and return exitCode().
86 If parse() returns \c true the command line was successfully parsed, its
87 values are well-defined, and they can be spectated with count(),
88 has(), value() and values().
90 \snippet doc/src/snippets/code/tools_patternist_qapplicationargumentparser.cpp 0
92 For arguments without a name(such as filename passed to the \c ls utility on Linux) add a
93 QApplicationArgument that does not have a name. The minimum and maximum occurrences will be
94 respected as usual and the type applies too.
96 QApplicationArgumentParser always has two options builtin: \c version and \c help.
98 \section1 Changing Parsing Convention
100 QApplicationArgumentParser by default parses the command line in the style
101 of Qt's utilities, where arguments are preceded by a single dash, and identified
102 by a single name. However, in some cases it might be of interest to parse
103 another style, such as the well-established UNIX \c getopt convention(\c -l
106 This can be achieved by sub-classing QApplicationArgumentParser and reimplementing
107 parse(). It would do the following:
110 \li Call input() to retrieve the strings the user specified on the command line.
111 \li Call declaredArguments() to retrieve the arguments that the implementor has
112 decided can be specified.
113 \li Parse and validate the input. Salt and pepper as per taste.
114 \li If an error occurred, call setExitCode() and return \c false.
115 \li Otherwise, call setExitCode(Success), provide access to the
116 arguments by calling setUsedArguments(), and return \c true. If a
117 help message was requested, call setExitCode(Success) and return \c false.
120 \sa QApplicationArgument, QCoreApplication
122 class QApplicationArgumentParserPrivate
124 Q_DECLARE_TR_FUNCTIONS(QApplicationArgumentParserPrivate)
126 // TODO Isn't it like ten times better with QHash<QApplicationArgument, QList<QVariant> >?
127 // TODO test QApplicationArgument::nameless()
128 typedef QList<QPair<QApplicationArgument, QVariant> > UsedList;
131 We initialize exitCode to ParseError such that we consciously flag success.
133 inline QApplicationArgumentParserPrivate(QApplicationArgumentParser *const master,
134 const QStringList &aInput) : exitCode(QApplicationArgumentParser::ParseError)
138 Q_ASSERT(!aInput.isEmpty());
141 QApplicationArgument nextNamelessArgument() const;
142 static QStringList argumentsFromLocal(const int argc, const char *const *const argv);
144 bool error(const QString &message);
145 static bool errorMessage(const QString &message);
146 static inline bool isSwitch(const QApplicationArgument &arg);
147 static inline QVariant conversionError(const QString &typeName,
148 const QString &input);
149 int count(const QApplicationArgument &arg) const;
150 bool contains(const QApplicationArgument &arg) const;
151 static inline bool isBuiltinVariant(const int type);
152 void displayVersion() const;
153 void displayHelp() const;
154 void parseNameless();
155 bool parseNamelessArguments(const QString &in);
157 QApplicationArgumentParser::ExitCode exitCode;
158 const QStringList input;
161 Since the QString is QApplicationArgument::name() anyway, why
164 QHash<QString, QApplicationArgument> declaredArguments;
166 QList<QApplicationArgument> declaredNamelessArguments;
168 UsedList usedArguments;
169 QString applicationDescription;
170 QString applicationVersion;
173 QApplicationArgumentParser *const q_ptr;
174 Q_DECLARE_PUBLIC(QApplicationArgumentParser)
176 static QString lineWrap(const QString &input,
177 const int leftIndent,
179 static QList<QApplicationArgument> builtinArguments();
182 QApplicationArgument QApplicationArgumentParserPrivate::nextNamelessArgument() const
184 /* Count how many nameless arguments we have so far. */
187 for(int i = 0; i < usedArguments.count(); ++i)
189 if(usedArguments.at(i).first.isNameless())
193 /* TODO this doesn't work for arguments that have more than one
194 * mandatory value(e.g nameless ones), since several values should
195 * then only count for one argument. */
196 for(int i = 0; i < declaredNamelessArguments.count(); ++i)
200 /* Skip the ones we already have processed. */
205 if(declaredNamelessArguments.at(i).isNameless())
206 return declaredNamelessArguments.at(i);
209 return QApplicationArgument();
212 int QApplicationArgumentParserPrivate::count(const QApplicationArgument &arg) const
214 const int len = usedArguments.count();
217 for(int i = 0; i < len; ++i)
219 if(usedArguments.at(i).first == arg)
227 Returns \c true if \a arg has appeared on the command line, not whether it has been declared.
229 bool QApplicationArgumentParserPrivate::contains(const QApplicationArgument &arg) const
231 const int len = usedArguments.count();
233 for(int i = 0; i < len; ++i)
235 if(usedArguments.at(i).first == arg)
243 Returns always \c false.
245 bool QApplicationArgumentParserPrivate::error(const QString &message)
247 exitCode = QApplicationArgumentParser::ParseError;
248 errorMessage(message);
249 return errorMessage(tr("Pass -help for information about the command line."));
253 Returns always \c false.
255 bool QApplicationArgumentParserPrivate::errorMessage(const QString &message)
257 QTextStream out(stderr, QIODevice::WriteOnly);
258 out << message << endl;
264 Determines whether \a arg carries a value or is on/off.
266 bool QApplicationArgumentParserPrivate::isSwitch(const QApplicationArgument &arg)
268 return arg.type() == QVariant::Invalid;
271 QVariant QApplicationArgumentParserPrivate::conversionError(const QString &typeName,
272 const QString &input)
274 errorMessage(tr("Cannot convert %1 to type %2.").arg(input, typeName));
278 bool QApplicationArgumentParserPrivate::isBuiltinVariant(const int type)
280 return type < int(QVariant::UserType);
284 TODO Temporary, replace with a function in QCoreApplication.
286 QStringList QApplicationArgumentParserPrivate::argumentsFromLocal(const int argc, const char *const *const argv)
292 for(int i = 0; i < argc; ++i)
293 result.append(QString::fromLocal8Bit(argv[i]));
298 void QApplicationArgumentParserPrivate::displayVersion() const
300 QTextStream out(stderr);
302 out << tr("%1 version %2 using Qt %3").arg(QCoreApplication::applicationName(), applicationVersion, QString::fromAscii(qVersion()))
308 \relates QApplicationArgument
310 qLess() functor for QApplicationArgument that considers the name.
313 class qLess <QApplicationArgument>
316 inline bool operator()(const QApplicationArgument &o1,
317 const QApplicationArgument &o2) const
319 return o1.name().compare(o2.name()) < 0;
323 void QApplicationArgumentParserPrivate::displayHelp() const
328 * When we want to line wrap, 80 minus a couple of characters. This should
329 * be suitable for vt100 compatible terminals.
334 * The initial " -" for each option.
339 * Pad for the brackets and space we use when we have a type.
341 ValueArgumentPadding = 4
344 QList<QApplicationArgument> args(declaredArguments.values());
345 args += builtinArguments();
347 /* Sort them, such that we get the nameless options at the end, and it
348 * generally looks tidy. */
351 /* This is the basic approach:
355 * -name <name-of-value-type> description
358 * name <type> description
360 * It all line-wraps at OutputWidth and the description is indented,
361 * where the highest indent is the length of the name plus length of the name
364 /* First we find the name with the largest width. */
367 QList<QApplicationArgument> nameless(declaredNamelessArguments);
370 /* Note, here the nameless arguments appear last, but are sorted
371 * with themselves. */
372 QList<QApplicationArgument> allArgs(args + nameless);
373 const int allArgsCount = allArgs.count();
375 for(int i = 0; i < allArgsCount; ++i)
377 const QApplicationArgument &at = allArgs.at(i);
378 const int nameLength = at.name().length();
379 const QString typeName(q_ptr->typeToName(at));
380 const int typeNameLength = typeName.length();
381 const int padding = at.type() == QVariant::Invalid ? 0 : ValueArgumentPadding;
382 maxWidth = qMax(maxWidth, nameLength + typeNameLength + padding);
385 QTextStream out(stderr);
387 << QString(IndentPadding, QLatin1Char(' '))
388 << QCoreApplication::applicationName()
389 << QLatin1String(" -- ")
390 << applicationDescription
394 /* One extra so we get some space between the overview and the options. */
397 const int indentWidth = maxWidth + 3;
399 /* Ok, print them out. */
400 for(int i = 0; i < allArgsCount; ++i)
402 const QApplicationArgument &at = allArgs.at(i);
403 /* " -name ". Indent a bit first, inspired by Qt's moc. */
404 const QString &name = at.name();
405 QString prolog(QLatin1String(" "));
407 /* We have a special case for the single dash. */
408 if(name == QChar::fromLatin1('-'))
413 prolog.append(QLatin1Char('-'));
415 prolog.append(name + QLatin1Char(' '));
418 if(at.type() != QVariant::Invalid)
420 /* It's not a switch, it has a value. */
422 /* Do we have a default value? If so, the argument is optional. */
423 const QString typeName(q_ptr->typeToName(at));
425 if(at.defaultValue().isValid())
426 prolog.append(QLatin1Char('[') + typeName + QLatin1Char(']'));
428 prolog.append(QLatin1Char('<') + typeName + QLatin1Char('>'));
429 // TODO Don't we want to display the default value?
431 prolog.append(QLatin1Char(' '));
434 prolog = prolog.leftJustified(indentWidth);
437 << lineWrap(at.description(), indentWidth, LineWrapAt)
443 Line wraps \a input and indents each line with \a leftIndent spaces, such that
444 the width does not go beyond \a maxWidth.
446 The addition of line endings is accounted for by the caller.
448 With QTextBoundaryFinder our line wrapping is relatively fancy, since it
449 does it the Unicode-way.
451 QString QApplicationArgumentParserPrivate::lineWrap(const QString &input,
452 const int leftIndent,
455 const QString indent(QString(leftIndent, QLatin1Char(' ')));
456 const int len = input.length();
457 const int textWidth = maxWidth - leftIndent;
460 QTextBoundaryFinder wrapFinder(QTextBoundaryFinder::Line, input);
461 wrapFinder.setPosition(textWidth);
463 if(input.length() + leftIndent <= maxWidth)
466 int from = wrapFinder.toPreviousBoundary();
467 output.append(input.left(from));
471 if((len - from) + leftIndent > maxWidth)
473 /* We need to line wrap. */
474 wrapFinder.setPosition(from + textWidth);
475 const int currentWidthPos = wrapFinder.toPreviousBoundary();
477 output.append(QLatin1Char('\n'));
478 output.append(indent);
479 output.append(input.mid(from, currentWidthPos - from).trimmed());
480 from += (currentWidthPos - from);
484 /* Append the remains. */
485 output.append(QLatin1Char('\n'));
486 output.append(indent);
487 output.append(input.mid(from).trimmed());
496 Returns a list with the builtin options that the parser has
498 QList<QApplicationArgument> QApplicationArgumentParserPrivate::builtinArguments()
500 QList<QApplicationArgument> result;
502 result.append(QApplicationArgument(QLatin1String("help"),
503 QLatin1String("Displays this help.")));
504 result.append(QApplicationArgument(QLatin1String("version"),
505 QLatin1String("Displays version information.")));
507 result.append(QApplicationArgument(QLatin1String("-"),
508 QLatin1String("When appearing, any following options are not interpreted as switches.")));
512 /* TODO, I don't think we want this function in a public API. Add it first when there is a demand. */
515 Creates a QApplicationArgumentParser that will parse the input in \a argc and \a argv.
516 These arguments should be passed directly from the \c main() function, and the decoding
517 of the input will be taken care of appropriately, depending on platform.
519 It is preferred to use the QStringList overload, in case the input is in the form of QStrings.
521 QApplicationArgumentParser::QApplicationArgumentParser(int argc, char **argv) : d(new QApplicationArgumentParserPrivate(this, QApplicationArgumentParserPrivate::argumentsFromLocal(argc, argv)))
523 Q_ASSERT_X(argv, Q_FUNC_INFO, "Argv cannot be null.");
524 Q_ASSERT_X(argc >= 1, Q_FUNC_INFO,
525 "argc must at least contain the application name. "
526 "Use the QStringList overload instead.");
532 Creates a QApplicationArgumentParser that will parse \a input. That is, instead of passing in \c argc
533 and \c argv, one can pass in a QStringList.
535 The caller guarantees that the first string in \a input is the name of the application.
537 QApplicationArgumentParser::QApplicationArgumentParser(const QStringList &input) : d(new QApplicationArgumentParserPrivate(this, input))
539 Q_ASSERT_X(input.count() >= 1, Q_FUNC_INFO,
540 "The input must at least contain the application name.");
544 This function is only of interest when subclassing.
546 Returns the strings that the user specified when starting the application. The first string
547 in the list is always the application name.
549 QStringList QApplicationArgumentParser::input() const
551 Q_ASSERT_X(d->input.count() >= 1, Q_FUNC_INFO, "Internal error, this should always hold true");
556 This function is only of interest when subclassing.
558 Sets the arguments that the user actually used on the command line to \a arguments.
559 The parse() function should call this, such that the result afterwards can be inspected
560 with for instance has() or count().
564 void QApplicationArgumentParser::setUsedArguments(const QList<QPair<QApplicationArgument, QVariant> > &arguments)
566 d->usedArguments = arguments;
570 This function is only of interest when subclassing.
572 Returns the arguments that the user used on the command line.
574 \sa setUsedArguments()
576 QList<QPair<QApplicationArgument, QVariant> > QApplicationArgumentParser::usedArguments() const
578 return d->usedArguments;
582 Destructs this QApplicationArgumentParser instance.
584 QApplicationArgumentParser::~QApplicationArgumentParser()
590 Adds \a argument to this parser.
592 This function is provided for convenience. It is equivalent to creating a QList
593 containing \a argument, append the existing arguments, and then call setDeclaredArguments() with the list.
595 \sa setDeclaredArguments()
597 void QApplicationArgumentParser::addArgument(const QApplicationArgument &argument)
599 if(argument.isNameless())
600 d->declaredNamelessArguments.append(argument);
602 d->declaredArguments.insert(argument.name(), argument);
606 Makes the parser recognize all arguments in \a arguments.
608 Any arguments previously set, are discarded.
610 \sa addArgument(), declaredArguments()
612 void QApplicationArgumentParser::setDeclaredArguments(const QList<QApplicationArgument> &arguments)
614 // TODO If we have a QHash internally, why not use it in the public API too?
615 const int len = arguments.count();
617 for(int i = 0; i < len; ++i)
618 d->declaredArguments.insert(arguments.at(i).name(), arguments.at(i));
622 Returns the arguments that this parser recognizes.
624 \sa addArgument(), setDeclaredArguments()
626 QList<QApplicationArgument> QApplicationArgumentParser::declaredArguments() const
628 return d->declaredArguments.values();
631 bool QApplicationArgumentParserPrivate::parseNamelessArguments(const QString &in)
633 /* It's a nameless options, such as simply "value". */
634 const QApplicationArgument nameless(nextNamelessArgument());
636 const QVariant val(q_ptr->convertToValue(nameless, in));
639 usedArguments.append(qMakePair(nameless, val));
643 return false; // TODO error msg?
647 Parses input() together with declaredArguments() and returns \c false if the caller
648 should exit immediately, which is the case of which an error was encountered or
649 help or the version was requested.
651 In the case of \c true was returned, valid arguments were supplied, and they can
652 be requested with functions like value(), values(), count() and has().
654 parse() must only be called once per QApplicationArgumentParser instance. The
655 second time it's called, the effects and return value are undefined.
657 \sa convertToValue(), typeToName()
659 bool QApplicationArgumentParser::parse()
661 const QChar sep(QLatin1Char('-'));
662 const int inputCount = d->input.count();
664 /* We skip the first entry, which is the application name. */
667 for(; i < inputCount; ++i)
669 const QString &in = d->input.at(i);
671 /* We have a single '-', signalling that the succeeding are not options. */
676 for(; i < inputCount; ++i)
678 if(!d->parseNamelessArguments(d->input.at(i)))
680 /* Process nameless options. Have code for this elsewhere, factor it out. */
686 if(in.startsWith(sep)) /* It is "-name". */
688 const QString name(in.mid(1));
690 if(name == QLatin1String("help"))
692 setExitCode(Success);
696 else if(name == QLatin1String("version"))
698 setExitCode(Success);
703 if(!d->declaredArguments.contains(name))
704 return d->error(QApplicationArgumentParserPrivate::tr("\"%1\" is an unknown argument.").arg(name));
706 const QApplicationArgument &arg = d->declaredArguments.value(name);
707 const int argCount = d->count(arg) + 1;
708 const int max = arg.maximumOccurrence();
710 if(argCount > max && max != -1)
712 /* Let's tailor the message for a common case. */
714 return d->error(QApplicationArgumentParserPrivate::tr("\"%1\" can only be used once.").arg(name));
716 return d->error(QApplicationArgumentParserPrivate::tr("\"%1\" can only be used %2 times.").arg(name, QString::number(max)));
719 if(QApplicationArgumentParserPrivate::isSwitch(arg))
721 d->usedArguments.append(qMakePair(arg, QVariant()));
729 return d->error(QApplicationArgumentParserPrivate::tr("\"%1\" must be followed by a value.").arg(name));
731 /* Okidoki, got a value, always something. Let's
732 * see if it validates. */
733 const QString &value = d->input.at(i);
735 const QVariant val(convertToValue(arg, value));
738 d->usedArguments.append(qMakePair(arg, val));
742 return false; // TODO error msg?
747 if(!d->parseNamelessArguments(in))
752 /* Check that all arguments that have been declared as mandatory, are actually
754 const QList<QApplicationArgument> declaredArguments(d->declaredArguments.values() + d->declaredNamelessArguments);
755 const int len = declaredArguments.count();
756 for(int i = 0; i < len; ++i)
758 const QApplicationArgument &at = declaredArguments.at(i);
759 const int min = at.minimumOccurrence();
760 const int max = at.maximumOccurrence(); // TODO What about infinite? -1
765 const int usedLen = d->usedArguments.count();
768 for(int u = 0; u < usedLen; ++u)
770 const QPair<QApplicationArgument, QVariant> &used = d->usedArguments.at(u);
775 const QString originalName(at.name());
776 const QString effectiveName(originalName.isEmpty() ? QLatin1Char('<') + typeToName(at) + QLatin1Char('>') : originalName);
780 /* For nameless options, we use the type as the name. Looks better. */
781 return d->error(QApplicationArgumentParserPrivate::tr("%1 must occur at least %2 times, therefore %3 times is insufficient.", "The number is for %2.", min)
782 .arg(effectiveName, QString::number(min), QString::number(useCount)));
784 else if(useCount > max)
785 return d->error(QApplicationArgumentParserPrivate::tr("%1 can occur at most %2 times", "", max).arg(effectiveName, QString::number(max)));
789 d->exitCode = Success;
794 This function is only of interest when subclassing.
796 parse() calls this function each time a value, that is \a input, on the command line needs to be
797 validated and subsequently converted to the type of \a argument. A descriptive error message will
798 be outputted if \a input cannot be converted to the required type.
800 The default implementation uses QVariant::canConvert() and QVariant::convert() for doing conversions.
802 QApplicationArgumentParser can be subclassed and this function subsequently overridden, to handle custom types.
804 If \a input isn't valid input for \a argument, this function returns a default constructed
807 \sa typeToName(), parse()
809 QVariant QApplicationArgumentParser::convertToValue(const QApplicationArgument &argument,
810 const QString &input) const
812 const int type = argument.type();
818 if(input == QLatin1String("true") || input == QChar::fromLatin1('1'))
819 return QVariant(true);
820 else if(input == QLatin1String("false") || input == QChar::fromLatin1('0'))
821 return QVariant(false);
823 return QApplicationArgumentParserPrivate::conversionError(typeToName(argument), input);
825 case QVariant::RegExp:
830 return QVariant(exp);
832 return QApplicationArgumentParserPrivate::conversionError(typeToName(argument), input);
836 const QUrl result(input);
839 return QVariant(result);
841 return QApplicationArgumentParserPrivate::conversionError(typeToName(argument), input);
845 QVariant result(input);
847 if(QApplicationArgumentParserPrivate::isBuiltinVariant(type) &&
848 result.convert(QVariant::Type(type)))
851 return QApplicationArgumentParserPrivate::conversionError(typeToName(argument), input);
857 This function is only of interest when subclassing.
859 convertToValue() calls this function when requiring a string for referring to \a type,
860 when generating user messages.
862 The implementation uses QVariant::typeToName() for most types, but special handles
863 some types, in order to let the message be better tailored for humans.
867 QString QApplicationArgumentParser::typeToName(const QApplicationArgument &argument) const
869 /* Personally I think nameForType() would be a better name but this is consistent
870 * with QVariant's function of the same name. */
871 const int type = argument.type();
875 case QVariant::RegExp:
876 return QApplicationArgumentParserPrivate::tr("regular expression");
878 return QLatin1String("URI");
879 case QVariant::String:
880 return QLatin1String("string");
883 if(QApplicationArgumentParserPrivate::isBuiltinVariant(type))
884 return QString::fromLatin1(QVariant::typeToName(QVariant::Type(type)));
886 return QLatin1String(QVariant(type, static_cast<void *>(0)).typeName());
892 Returns the default value for \a argument. The default implementation returns
893 QApplicationArgument::defaultValue(), if \a argument has been added to this parser.
895 Overriding this function can be useful if creating the default value is resource
896 consuming, such as opening a file.
898 QVariant QApplicationArgumentParser::defaultValue(const QApplicationArgument &argument) const
900 return d->declaredArguments.value(argument.name()).defaultValue();
904 Returns the count of how many times \a argument was used on the command line.
908 int QApplicationArgumentParser::count(const QApplicationArgument &argument) const
910 Q_ASSERT_X(d->declaredArguments.contains(argument.name()) ||
911 d->declaredNamelessArguments.contains(argument), Q_FUNC_INFO,
912 "The argument isn't known to the parser. Has addArgument() been called?");
913 return d->count(argument);
917 Returns \c true if \a argument has been
918 specified one or more times on the command line, otherwise \a false.
922 bool QApplicationArgumentParser::has(const QApplicationArgument &argument) const
924 Q_ASSERT_X(d->declaredArguments.contains(argument.name()) ||
925 d->declaredNamelessArguments.contains(argument), Q_FUNC_INFO,
926 "The argument isn't known to the parser. Has addArgument() been called?");
927 return d->contains(argument);
935 QVariant QApplicationArgumentParser::value(const QApplicationArgument &argument) const
937 Q_ASSERT_X(d->declaredArguments.contains(argument.name()) ||
938 d->declaredNamelessArguments.contains(argument), Q_FUNC_INFO,
939 "The argument isn't known to the parser. Has addArgument() been called?");
941 const int len = d->usedArguments.count();
943 for(int i = 0; i < len; ++i)
945 if(d->usedArguments.at(i).first == argument)
946 return d->usedArguments.at(i).second;
949 return defaultValue(argument);
956 QVariantList QApplicationArgumentParser::values(const QApplicationArgument &argument) const
958 Q_ASSERT_X(d->declaredArguments.contains(argument.name()) ||
959 d->declaredNamelessArguments.contains(argument),
961 "The argument isn't known to the parser. Has addArgument() been called?");
963 const int len = d->usedArguments.count();
966 for(int i = 0; i < len; ++i)
968 if(d->usedArguments.at(i).first == argument)
969 result.append(d->usedArguments.at(i).second);
972 // TODO how do we handle default values?
977 After parse() has been called, this function returns a code that can be used to
978 exit \c main() with. It returns zero upon success or if help was requested, and
979 otherwise a value signalling failure.
981 QApplicationArgumentParser::ExitCode QApplicationArgumentParser::exitCode() const
987 This function is only of interest when subclassing.
989 Makes exitCode() return \a code.
991 void QApplicationArgumentParser::setExitCode(ExitCode code)
997 Sets the application description to \a description.
999 The application description is a sentence or two used for help and version
1000 messages, that briefly describes the application.
1002 The default is the empty string.
1004 void QApplicationArgumentParser::setApplicationDescription(const QString &description)
1006 d->applicationDescription = description;
1010 Sets the application version to \a version.
1012 This string, which is arbitrary but typically is "1.0" or so, is used when
1013 generating a version statement.
1015 void QApplicationArgumentParser::setApplicationVersion(const QString &version)
1017 d->applicationVersion = version;
1021 Writes out \a message to \c stderr.
1023 void QApplicationArgumentParser::message(const QString &message) const
1025 d->errorMessage(message);