CopperSpice API  1.9.1
QCommandLineParser Class Reference

Provides a way to process command line options. More...

Public Types

enum  SingleDashWordOptionMode
 

Public Methods

 QCommandLineParser ()
 
 ~QCommandLineParser ()
 
QCommandLineOption addHelpOption ()
 
bool addOption (const QCommandLineOption &option)
 
void addPositionalArgument (const QString &name, const QString &description, const QString &syntax=QString ())
 
QCommandLineOption addVersionOption ()
 
QString applicationDescription () const
 
void clearPositionalArguments ()
 
QString errorText () const
 
QString helpText () const
 
bool isSet (const QCommandLineOption &option) const
 
bool isSet (const QString &name) const
 
QStringList optionNames () const
 
bool parse (const QStringList &arguments)
 
QStringList positionalArguments () const
 
void process (const QCoreApplication &app)
 
void process (const QStringList &arguments)
 
void setApplicationDescription (const QString &description)
 
void setSingleDashWordOptionMode (SingleDashWordOptionMode parsingMode)
 
void showHelp (int exitCode=0)
 
void showVersion ()
 
QStringList unknownOptionNames () const
 
QString value (const QCommandLineOption &option) const
 
QString value (const QString &optionName) const
 
QStringList values (const QCommandLineOption &option) const
 
QStringList values (const QString &optionName) const
 

Detailed Description

The QCommandLineParser class is used to process the command line arguments passed by the user when starting an application. This class contains methods to define a set of options and positional arguments, parse the passed command line arguments, and store which options and values were passed.

The QCoreApplication::arguments() method can be used to return the passed command line arguments as a list of strings. This might be useful if your application needs to inspect or adjust any of the options or values passed by the user.

Optional Arguments

Options on the command line start with a single or double dash followed by the option name. QCommandLineParser can process arguments with short names, long names, more than one name for the same option, and the option values.

Positional Arguments

Any argument which is not an option and does not start with a dash, is stored as a positional argument. A double dash followed by a blank space indicates all of the following arguments will be treated as positional arguments, even if they happen to start with a dash.

Short Options

The name of a short option is a single letter. As an example, the "v" option is specified by passing -v which is often used to turn on verbose mode.

In the default parsing mode multiple short options can be written as a single argument. If the user passes -abc it is equivalent to passing -a -b -c.

Long Options

The name of a long option is two or more letters which can not be combined with other options in a single argument. As an example, the "verbose" option is specified by passing -verbose or --verbose to turn on verbose mode.

Passing Values

Passing values for an option can be done using an equal sign or a space. If a value is required, it must be passed on the command line by the user.

-d=all OR --debug=all // equal sign
-d all OR --debug all // space

Turning Off an Option

QCommandLineParser does not automatically support turning an option off with the following syntax: --disable-option or --no-option. Turning on or off functionality is done by adding a new option and then implementing the appropriate actions.

Example

The following example code uses a variety of the methods which are available in the QCommandLineParser class.

There are currently two built in options for this class which can be enabled. The --version is added by addVersionOption() and --help by calling addHelpOption(). When the user passes either the help or version options or if there is an error parsing the command line, the help text will be displayed and then the application will terminate using std::exit().

int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
parser.setApplicationDescription("Program will copy a source file to a destination location");
// enable built in options
parser.addHelpOption();
parser.addVersionOption();
// positional arguments
parser.addPositionalArgument("source", "Source file to copy.");
parser.addPositionalArgument("destination", "Destination directory.");
// option with a single name (-p)
QCommandLineOption showProgressOption("p", "Show the progress bar during the copy process.");
parser.addOption(showProgressOption);
// option with multiple names (-f, --force)
QCommandLineOption forceOption(QStringList() << "f" << "force", "Overwrite existing files.");
parser.addOption(forceOption);
// option with a value
QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory",
"Copy all source files into <directory>.", "directory");
parser.addOption(targetDirectoryOption);
// process command line arguments passed by the user
parser.process(app);
// values for the source and destination
const QStringList args = parser.positionalArguments();
bool showProgress = parser.isSet(showProgressOption);
bool force = parser.isSet(forceOption);
QString targetDir = parser.value(targetDirectoryOption);
. . .
}
See also
QCommandLineOption, QCoreApplication

Member Enumeration Documentation

This enum describes the way the parser interprets command line options that use a single dash followed by multiple letters, as in "-abc".

ConstantValueDescription
QCommandLineParser::ParseAsCompactedShortOptions 0

Passing -abc is equivalent to passing -a -b -c, if none of the options have a value.

If option "a" has a value then -abc is interpreted as -a=bc which is the short option for "a" followed by the value "bc".

QCommandLineParser::ParseAsLongOptions 1 Passing -abc is always equivalent to passing --abc
See also
setSingleDashWordOptionMode()

Constructor & Destructor Documentation

QCommandLineParser::QCommandLineParser ( )

Constructs an empty QCommandLineParser.

QCommandLineParser::~QCommandLineParser ( )

Destroys the QCommandLineParser.

Method Documentation

QCommandLineOption QCommandLineParser::addHelpOption ( )

Adds the help options -h and --help. On Windows an additional option for -? will be added. These options will be configured automatically by QCommandLineParser.

Call the method setApplicationDescription() to change the application description which is displayed by the helpText() method.

bool QCommandLineParser::addOption ( const QCommandLineOption option)

Adds option to the QCommandLineParser. Returns true if adding the option was successful, otherwise returns false. Adding an option will fail if the name is empty or the name conflicts with an existing option.

For more information about options, refer to Optional Arguments.

void QCommandLineParser::addPositionalArgument ( const QString name,
const QString description,
const QString syntax = QString() 
)

Defines additional command line arguments which will be included in the help text. The values for name and description will appear under the Arguments section of the help text. If syntax is not empty this string will be appended to the Usage line, otherwise the name will be appended.

// code in the Editor program
parser.addPositionalArgument("fileName", "File to open when the Editor starts.");
// Usage: Editor fileName
//
// Arguments:
// fileName File to open when the Editor starts.
// code in the WebBrowser program
parser.addPositionalArgument("urls", "Optional list of URLs to open.", "[urls...]");
// Usage: WebBrowser [urls...]
//
// Arguments:
// urls Optional list of URLs to open.
// code in the cp program
parser.addPositionalArgument("source", "Source file to copy.");
parser.addPositionalArgument("destination", "Destination directory.");
// Usage: cp source destination
//
// Arguments:
// source Source file to copy.
// destination Destination directory.
See also
addHelpOption(), helpText()
QCommandLineOption QCommandLineParser::addVersionOption ( )

Adds -v or --version to the list of options. Calling this method will display the version of the application. Returns the QCommandLineOption object which can be passed to isSet() to determine if the user passed -v or --version on the command line.

The value for version is set by calling QCoreApplication::setApplicationVersion().

For more information about options, refer to Optional Arguments.

QString QCommandLineParser::applicationDescription ( ) const

Returns the application description which can be set by calling setApplicationDescription().

void QCommandLineParser::clearPositionalArguments ( )

Clears the definitions of additional arguments from the help text. This is used when a program supports multiple commands with different options.

QCoreApplication app(argc, argv);
parser.addPositionalArgument("command", "Command to execute.");
// call parse() to find the positional arguments
const QStringList args = parser.positionalArguments();
const QString command = args.isEmpty() ? QString() : args.first();
if (command == "resize") {
parser.addPositionalArgument("resize", "Resize the object to a new size.", "resize [resize_options]");
parser.addOption(QCommandLineOption("size", "New size.", "new_size"));
parser.process(app);
}

The code shown above will generate the following help, depending on the command line values entered by the user.

$ someProgram --help
Usage: someProgram command
Arguments:
command Command to execute.
$ someProgram resize --help
Usage: someProgram resize [resize_options]
Options:
--size <size> New size.
Arguments:
resize Resize the object to a new size.
QString QCommandLineParser::errorText ( ) const

Returns the translated error text. This should only be called if parse() returns false.

QString QCommandLineParser::helpText ( ) const

Returns a string containing the complete help information.

See also
showHelp()
bool QCommandLineParser::isSet ( const QCommandLineOption option) const

The method checks if the given option was passed to the application on the command line. Returns true if the option was set, otherwise returns false.

QCoreApplication app(argc, argv);
QCommandLineOption verboseOption("verbose");
parser.addOption(verboseOption);
parser.process(app);
// test if the option was set
bool verbose = parser.isSet(verboseOption);
bool QCommandLineParser::isSet ( const QString name) const

The method checks if the option with the given name was passed to the application on the command line. Returns true if the option was set, otherwise returns false. This method will return false if the name is not an existing option.

The name can be any long or short name of any option which was added with addOption(). A given option can have multiple names.

bool verbose = parser.isSet("verbose");
QStringList QCommandLineParser::optionNames ( ) const

Returns a list of strings which are the options that were passed on the command line. The options in the list are in the order in which they were found. Options may appear more than once in this list if they were present more than once on the command line. The elements in this list do not include any preceding dash characters.

Elements in the list can be passed to value() or values() to retrieve the corresponding value, if one exists.

bool QCommandLineParser::parse ( const QStringList arguments)

Parses the given list of arguments. The QStringList is created in your application and it does not need to match the actual command line arguments. The first element in the list should be the name of the executable, however it can be empty. Returns false when there is a parse error, unknown option, or missing value, otherwise returns true. The application must handle any errors using errorText() if false is returned.

Calling this method can be useful when your application wants to ignore unknown options. Most programs should call process() instead of using this parse() method.

QStringList QCommandLineParser::positionalArguments ( ) const

Returns a list of positional arguments. These are all of the command line arguments which were not recognized as an option.

void QCommandLineParser::process ( const QCoreApplication app)

When calling this method pass app which is the variable used when constructing your QApplication. The command line arguments will be retrieved automatically, your code does not need to call QCoreApplication::arguments().

QApplication myApp(argc, argv);
parser.process(myApp);
void QCommandLineParser::process ( const QStringList arguments)

Reads the arguments and stores them in the QCommandLineParser as if they were passed on the command line. This method will parse arguments and handle any errors.

See also
QCoreApplication::arguments(), parse()
void QCommandLineParser::setApplicationDescription ( const QString description)

Sets the application description which is shown by helpText().

See also
applicationDescription()
void QCommandLineParser::setSingleDashWordOptionMode ( SingleDashWordOptionMode  parsingMode)

Sets the QCommandLineParser to the given parsingMode. If this method is called after calling process() or parse(), it will have no effect.

void QCommandLineParser::showHelp ( int  exitCode = 0)

Displays the help information and then exits the application. The exit code is set to exitCode. A value of 0 should be used when the user requested to view the help. Other values should be used to indicate an error.

This method is automatically called by process() when the user starts the application and passes the -h or --help option.

See also
addHelpOption(), helpText()
void QCommandLineParser::showVersion ( )

Displays the version information from QCoreApplication::applicationVersion() and then exits the application. The exit code is set to EXIT_SUCCESS (0).

This method is automatically called by process() when the user starts the application and passes the -v or --version option.

See also
addVersionOption()
QStringList QCommandLineParser::unknownOptionNames ( ) const

Returns a list of strings which were options passed on the command line and not recognized as part of the current QCommandLineParser. The options in the list are in the order in which they were found. Options may appear more than once in this list if they were present more than once on the command line. The elements in this list do not include any preceding dash characters.

For any long options with values, the value will be dropped and only the long name will appear in the list.

See also
optionNames()
QString QCommandLineParser::value ( const QCommandLineOption option) const

Returns the value for the given option or an empty string if no value was passed on the command line. When the same option is passed more then once on the command line, the last value found for that option is returned. If the option was not specified on the command line the default value is returned. An empty string is returned if the option does not take a value.

See also
values(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
QString QCommandLineParser::value ( const QString optionName) const

Returns the value for the given optionName or an empty string if no value was passed on the command line. When the same option is passed more then once on the command line, the last value found for that option is returned. If the option was not specified on the command line the default value is returned. An empty string is returned if the option does not take a value.

The name can be any long or short name of any option which was added with addOption(). If the name is not recognized or the option was not passed on the command line, an empty string is returned.

See also
values(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
QStringList QCommandLineParser::values ( const QCommandLineOption option) const

Returns a list of values for the given option or an empty list if no value was passed on the command line. When the same option is passed more then once on the command line all values found for that option are returned. If the option was not specified on the command line the default value is returned. An empty list is returned if the option does not take a value.

See also
value(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
QStringList QCommandLineParser::values ( const QString optionName) const

Returns a list of values for the given optionName or an empty list if no value was passed on the command line. When the same option is passed more then once on the command line all values found for that option are returned. If the option was not specified on the command line the default value is returned. An empty list is returned if the option does not take a value.

The name can be any long or short name of any option which was added with addOption(). If the name is not recognized or the option was not passed on the command line, an empty list is returned.

See also
value(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()