QCommandLineParser 類

The QCommandLineParser class provides a means for handling the command line options. 更多...

頭: #include <QCommandLineParser>
qmake: QT += core
Since: Qt 5.2

公共類型

enum OptionsAfterPositionalArgumentsMode { ParseAsOptions, ParseAsPositionalArguments }
enum SingleDashWordOptionMode { ParseAsCompactedShortOptions, ParseAsLongOptions }

公共函數

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

詳細描述

The QCommandLineParser class provides a means for handling the command line options.

QCoreApplication provides the command-line arguments as a simple list of strings. QCommandLineParser provides the ability to define a set of options, parse the command-line arguments, and store which options have actually been used, as well as option values.

不是選項的任何自變量 (即:開頭不是 - ) 會以 "位置自變量" 形式被存儲。

剖析器處理短名稱、長名稱、同一選項的多個名稱、及選項值。

Options on the command line are recognized as starting with a single or double - character(s). The option - (single dash alone) is a special case, often meaning standard input, and not treated as an option. The parser will treat everything after the option -- (雙破摺號) 為位置自變量。

短選項是單字母。選項 v 的指定是通過傳遞 -v 在命令行。在默認剖析模式,短選項能以緊湊形式編寫,例如 -abc 相當於 -a -b -c . The parsing mode for can be set to ParseAsLongOptions ,在這種情況下 -abc 會被解析成長選項 abc .

長選項多於一字母長,且無法壓縮在一起。長選項 verbose 的傳遞如 --verbose or -verbose .

Passing values to options can be done using the assignment operator: -v=value --verbose=value , or a space: -v value --verbose value , i.e. the next argument is used as value (even if it starts with a - ).

剖析器不支持可選值 -,若把選項設為要求值,則必須存在值。若把這種選項放在最後且沒有值,選項會被視為未指定。

The parser does not automatically support negating or disabling long options by using the format --disable-option or --no-option . However, it is possible to handle this case explicitly by making an option with no-option as one of its names, and handling the option explicitly.

範例:

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("my-copy-program");
    QCoreApplication::setApplicationVersion("1.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);
    // ...
}
					

If your compiler supports the C++11 standard, the three addOption () calls in the above example can be simplified:

    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")},
    });
					

Known limitation: the parsing of Qt options inside QCoreApplication and subclasses happens before QCommandLineParser exists, so it can't take it into account. This means any option value that looks like a builtin Qt option, will be treated by QCoreApplication as a builtin Qt option. Example: --profile -reverse will lead to QGuiApplication seeing the -reverse option set, and removing it from QCoreApplication::arguments () 先於 QCommandLineParser defines the profile option and parses the command line.

如何在復雜應用程序中使用 QCommandLineParser

In practice, additional error checking needs to be performed on the positional arguments and option values. For example, ranges of numbers should be checked.

It is then advisable to introduce a function to do the command line parsing which takes a struct or class receiving the option values returning an enumeration representing the result. The dnslookup example of the QtNetwork module illustrates this:

struct DnsQuery
{
    DnsQuery() : type(QDnsLookup::A) {}
    QDnsLookup::Type type;
    QHostAddress nameServer;
    QString name;
};
enum CommandLineParseResult
{
    CommandLineOk,
    CommandLineError,
    CommandLineVersionRequested,
    CommandLineHelpRequested
};
CommandLineParseResult parseCommandLine(QCommandLineParser &parser, DnsQuery *query, QString *errorMessage)
{
    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
    const QCommandLineOption nameServerOption("n", "The name server to use.", "nameserver");
    parser.addOption(nameServerOption);
    const QCommandLineOption typeOption("t", "The lookup type.", "type");
    parser.addOption(typeOption);
    parser.addPositionalArgument("name", "The name to look up.");
    const QCommandLineOption helpOption = parser.addHelpOption();
    const QCommandLineOption versionOption = parser.addVersionOption();
    if (!parser.parse(QCoreApplication::arguments())) {
        *errorMessage = parser.errorText();
        return CommandLineError;
    }
    if (parser.isSet(versionOption))
        return CommandLineVersionRequested;
    if (parser.isSet(helpOption))
        return CommandLineHelpRequested;
    if (parser.isSet(nameServerOption)) {
        const QString nameserver = parser.value(nameServerOption);
        query->nameServer = QHostAddress(nameserver);
        if (query->nameServer.isNull() || query->nameServer.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
            *errorMessage = "Bad nameserver address: " + nameserver;
            return CommandLineError;
        }
    }
    if (parser.isSet(typeOption)) {
        const QString typeParameter = parser.value(typeOption);
        const int type = typeFromParameter(typeParameter.toLower());
        if (type < 0) {
            *errorMessage = "Bad record type: " + typeParameter;
            return CommandLineError;
        }
        query->type = static_cast<QDnsLookup::Type>(type);
    }
    const QStringList positionalArguments = parser.positionalArguments();
    if (positionalArguments.isEmpty()) {
        *errorMessage = "Argument 'name' missing.";
        return CommandLineError;
    }
    if (positionalArguments.size() > 1) {
        *errorMessage = "Several 'name' arguments specified.";
        return CommandLineError;
    }
    query->name = positionalArguments.first();
    return CommandLineOk;
}
					

In the main function, help should be printed to the standard output if the help option was passed and the application should return the exit code 0.

If an error was detected, the error message should be printed to the standard error output and the application should return an exit code other than 0.

    QCoreApplication::setApplicationVersion(QT_VERSION_STR);
    QCoreApplication::setApplicationName(QCoreApplication::translate("QDnsLookupExample", "DNS Lookup Example"));
    QCommandLineParser parser;
    parser.setApplicationDescription(QCoreApplication::translate("QDnsLookupExample", "An example demonstrating the class QDnsLookup."));
    DnsQuery query;
    QString errorMessage;
    switch (parseCommandLine(parser, &query, &errorMessage)) {
    case CommandLineOk:
        break;
    case CommandLineError:
        fputs(qPrintable(errorMessage), stderr);
        fputs("\n\n", stderr);
        fputs(qPrintable(parser.helpText()), stderr);
        return 1;
    case CommandLineVersionRequested:
        printf("%s %s\n", qPrintable(QCoreApplication::applicationName()),
               qPrintable(QCoreApplication::applicationVersion()));
        return 0;
    case CommandLineHelpRequested:
        parser.showHelp();
        Q_UNREACHABLE();
    }
					

A special case to consider here are GUI applications on Windows and mobile platforms. These applications may not use the standard output or error channels since the output is either discarded or not accessible.

在 Windows, QCommandLineParser uses message boxes to display usage information and errors if no console window can be obtained.

For other platforms, it is recommended to display help texts and error messages using a QMessageBox . To preserve the formatting of the help text, rich text with <pre> elements should be used:

switch (parseCommandLine(parser, &query, &errorMessage)) {
case CommandLineOk:
    break;
case CommandLineError:
    QMessageBox::warning(0, QGuiApplication::applicationDisplayName(),
                         "<html><head/><body><h2>" + errorMessage + "</h2><pre>"
                         + parser.helpText() + "</pre></body></html>");
    return 1;
case CommandLineVersionRequested:
    QMessageBox::information(0, QGuiApplication::applicationDisplayName(),
                             QGuiApplication::applicationDisplayName() + ' '
                             + QCoreApplication::applicationVersion());
    return 0;
case CommandLineHelpRequested:
    QMessageBox::warning(0, QGuiApplication::applicationDisplayName(),
                         "<html><head/><body><pre>"
                         + parser.helpText() + "</pre></body></html>");
    return 0;
}
					

However, this does not apply to the dnslookup example, because it is a console application.

另請參閱 QCommandLineOption and QCoreApplication .

成員類型文檔編製

enum QCommandLineParser:: OptionsAfterPositionalArgumentsMode

This enum describes the way the parser interprets options that occur after positional arguments.

常量 描述
QCommandLineParser::ParseAsOptions 0 application argument --opt -t is interpreted as setting the options opt and t , just like application --opt -t argument would do. This is the default parsing mode. In order to specify that --opt and -t are positional arguments instead, the user can use -- , as in application argument -- --opt -t .
QCommandLineParser::ParseAsPositionalArguments 1 application argument --opt is interpreted as having two positional arguments, argument and --opt . This mode is useful for executables that aim to launch other executables (e.g. wrappers, debugging tools, etc.) or that support internal commands followed by options for the command. argument is the name of the command, and all options occurring after it can be collected and parsed by another command line parser, possibly in another executable.

該枚舉在 Qt 5.6 引入或被修改。

另請參閱 setOptionsAfterPositionalArgumentsMode ().

enum QCommandLineParser:: SingleDashWordOptionMode

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

常量 描述
QCommandLineParser::ParseAsCompactedShortOptions 0 -abc is interpreted as -a -b -c , i.e. as three short options that have been compacted on the command-line, if none of the options take a value. If a takes a value, then it is interpreted as -a bc , i.e. the short option a followed by the value bc . This is typically used in tools that behave like compilers, in order to handle options such as -DDEFINE=VALUE or -I/include/path . This is the default parsing mode. New applications are recommended to use this mode.
QCommandLineParser::ParseAsLongOptions 1 -abc is interpreted as --abc , i.e. as the long option named abc . This is how Qt's own tools (uic, rcc...) have always been parsing arguments. This mode should be used for preserving compatibility in applications that were parsing arguments in such a way. There is an exception if the a option has the QCommandLineOption::ShortOptionStyle flag set, in which case it is still interpreted as -a bc .

另請參閱 setSingleDashWordOptionMode ().

成員函數文檔編製

QCommandLineParser:: QCommandLineParser ()

構造命令行剖析器對象。

QCommandLineParser:: ~QCommandLineParser ()

銷毀命令行剖析器對象。

QCommandLineOption QCommandLineParser:: addHelpOption ()

Adds the help option ( -h , --help and -? on Windows) This option is handled automatically by QCommandLineParser .

記得使用 setApplicationDescription to set the application description, which will be displayed when this option is used.

範例:

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("my-copy-program");
    QCoreApplication::setApplicationVersion("1.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);
    // ...
}
					

Returns the option instance, which can be used to call isSet ().

bool QCommandLineParser:: addOption (const QCommandLineOption & option )

添加選項 option 到查找,當剖析時。

返迴 true if adding the option was successful; otherwise returns false .

Adding the option fails if there is no name attached to the option, or the option has a name that clashes with an option name added before.

bool QCommandLineParser:: addOptions (const QList < QCommandLineOption > & options )

Adds the options to look for while parsing. The options are specified by the parameter options .

返迴 true if adding all of the options was successful; otherwise returns false .

見文檔編製為 addOption () for when this function may fail.

該函數在 Qt 5.4 引入。

void QCommandLineParser:: addPositionalArgument (const QString & name , const QString & 描述 , const QString & syntax = QString())

Defines an additional argument to the application, for the benefit of the help text.

自變量 name and 描述 will appear under the Arguments: section of the help. If syntax is specified, it will be appended to the Usage line, otherwise the name will be appended.

範例:

// Usage: image-editor file
//
// Arguments:
//   file                  The file to open.
parser.addPositionalArgument("file", QCoreApplication::translate("main", "The file to open."));
// Usage: web-browser [urls...]
//
// Arguments:
//   urls                URLs to open, optionally.
parser.addPositionalArgument("urls", QCoreApplication::translate("main", "URLs to open, optionally."), "[urls...]");
// Usage: cp source destination
//
// Arguments:
//   source                Source file to copy.
//   destination           Destination directory.
parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));
					

另請參閱 addHelpOption () 和 helpText ().

QCommandLineOption QCommandLineParser:: addVersionOption ()

添加 -v / --version 選項,顯示應用程序的版本字符串。

此選項的自動處理是通過 QCommandLineParser .

可以設置實際版本字符串通過使用 QCoreApplication::setApplicationVersion ().

Returns the option instance, which can be used to call isSet ().

QString QCommandLineParser:: applicationDescription () const

返迴的應用程序描述設置在 setApplicationDescription ().

另請參閱 setApplicationDescription ().

void QCommandLineParser:: clearPositionalArguments ()

Clears the definitions of additional arguments from the help text.

This is only needed for the special case of tools which support multiple commands with different options. Once the actual command has been identified, the options for this command can be defined, and the help text for the command can be adjusted accordingly.

範例:

QCoreApplication app(argc, argv);
QCommandLineParser parser;
parser.addPositionalArgument("command", "The command to execute.");
// Call parse() to find out the positional arguments.
parser.parse(QCoreApplication::arguments());
const QStringList args = parser.positionalArguments();
const QString command = args.isEmpty() ? QString() : args.first();
if (command == "resize") {
    parser.clearPositionalArguments();
    parser.addPositionalArgument("resize", "Resize the object to a new size.", "resize [resize_options]");
    parser.addOption(QCommandLineOption("size", "New size.", "new_size"));
    parser.process(app);
    // ...
}
/*
This code results in context-dependent help:
$ tool --help
Usage: tool command
Arguments:
  command  The command to execute.
$ tool resize --help
Usage: tool resize [resize_options]
Options:
  --size <size>  New size.
Arguments:
  resize         Resize the object to a new size.
*/
					

QString QCommandLineParser:: errorText () const

Returns a translated error text for the user. This should only be called when parse () 返迴 false .

QString QCommandLineParser:: helpText () const

返迴包含完整幫助信息的字符串。

另請參閱 showHelp ().

bool QCommandLineParser:: isSet (const QString & name ) const

校驗是否選項 name 傳遞給應用程序。

返迴 true 若選項 name 有設置,false 否則。

The name provided can be any long or short name of any option that was added with addOption() . All the options names are treated as being equivalent. If the name is not recognized or that option was not present, false is returned.

範例:

bool verbose = parser.isSet("verbose");
					

bool QCommandLineParser:: isSet (const QCommandLineOption & option ) const

這是重載函數。

校驗是否 option 傳遞給應用程序。

返迴 true option 有設置,false 否則。

這是校驗用於無值選項的推薦方式。

範例:

QCoreApplication app(argc, argv);
QCommandLineParser parser;
QCommandLineOption verboseOption("verbose");
parser.addOption(verboseOption);
parser.process(app);
bool verbose = parser.isSet(verboseOption);
					

QStringList QCommandLineParser:: optionNames () const

返迴找到的選項名列錶。

This returns a list of all the recognized option names found by the parser, in the order in which they were found. For any long options that were in the form {--option=value}, the value part will have been dropped.

The names in this list do not include the preceding dash characters. Names may appear more than once in this list if they were encountered more than once by the parser.

Any entry in the list can be used with value() or with values() to get any relevant option values.

bool QCommandLineParser:: parse (const QStringList & arguments )

剖析命令行 arguments .

大多數程序不需要調用這,簡單調用 process () 就夠瞭。

parse() is more low-level, and only does the parsing. The application will have to take care of the error handling, using errorText () 若 parse() 返迴 false . This can be useful for instance to show a graphical error message in graphical programs.

Calling parse() instead of process () can also be useful in order to ignore unknown options temporarily, because more option definitions will be provided later on (depending on one of the arguments), before calling process ().

彆忘瞭 arguments 必須以可執行文件名開頭 (雖然可忽略)。

返迴 false in case of a parse error (unknown option or missing value); returns true 否則。

另請參閱 process ().

QStringList QCommandLineParser:: positionalArguments () const

返迴位置自變量列錶。

These are all of the arguments that were not recognized as part of an option.

void QCommandLineParser:: process (const QStringList & arguments )

處理命令行 arguments .

除瞭剖析選項 (像 parse ()), this function also handles the builtin options and handles errors.

內置選項包括 --version if addVersionOption 被調用和 --help if addHelpOption 被調用。

When invoking one of these options, or when an error happens (for instance an unknown option was passed), the current process will then stop, using the exit() function.

另請參閱 QCoreApplication::arguments () 和 parse ().

void QCommandLineParser:: process (const QCoreApplication & app )

這是重載函數。

命令行的獲得是來自 QCoreApplication 實例 app .

void QCommandLineParser:: setApplicationDescription (const QString & 描述 )

設置應用程序 描述 展示通過 helpText ().

另請參閱 applicationDescription ().

void QCommandLineParser:: setOptionsAfterPositionalArgumentsMode ( OptionsAfterPositionalArgumentsMode parsingMode )

把剖析模式設為 parsingMode 。這的調用必須先於 process () 或 parse ().

該函數在 Qt 5.6 引入。

void QCommandLineParser:: setSingleDashWordOptionMode ( SingleDashWordOptionMode singleDashWordOptionMode )

把剖析模式設為 singleDashWordOptionMode 。這的調用必須先於 process () 或 parse ().

void QCommandLineParser:: showHelp ( int exitCode = 0)

Displays the help information, and exits the application. This is automatically triggered by the --help option, but can also be used to display the help when the user is not invoking the application correctly. The exit code is set to exitCode . It should be set to 0 if the user requested to see the help, and to any other value in case of an error.

另請參閱 helpText ().

void QCommandLineParser:: showVersion ()

顯示版本信息從 QCoreApplication::applicationVersion (), and exits the application. This is automatically triggered by the --version option, but can also be used to display the version when not using process (). The exit code is set to EXIT_SUCCESS (0).

該函數在 Qt 5.4 引入。

另請參閱 addVersionOption ().

QStringList QCommandLineParser:: unknownOptionNames () const

返迴未知選項名列錶。

This list will include both long an short name options that were not recognized. For any long options that were in the form {--option=value}, the value part will have been dropped and only the long name is added.

The names in this list do not include the preceding dash characters. Names may appear more than once in this list if they were encountered more than once by the parser.

另請參閱 optionNames ().

QString QCommandLineParser:: value (const QString & optionName ) const

Returns the option value found for the given option name optionName , or an empty string if not found.

The name provided can be any long or short name of any option that was added with addOption() . All the option names are treated as being equivalent. If the name is not recognized or that option was not present, an empty string is returned.

For options found by the parser, the last value found for that option is returned. If the option wasn't specified on the command line, the default value is returned.

An empty string is returned if the option does not take a value.

另請參閱 values (), QCommandLineOption::setDefaultValue (),和 QCommandLineOption::setDefaultValues ().

QString QCommandLineParser:: value (const QCommandLineOption & option ) const

這是重載函數。

Returns the option value found for the given option , or an empty string if not found.

For options found by the parser, the last value found for that option is returned. If the option wasn't specified on the command line, the default value is returned.

An empty string is returned if the option does not take a value.

另請參閱 values (), QCommandLineOption::setDefaultValue (),和 QCommandLineOption::setDefaultValues ().

QStringList QCommandLineParser:: values (const QString & optionName ) const

Returns a list of option values found for the given option name optionName , or an empty list if not found.

The name provided can be any long or short name of any option that was added with addOption() . All the options names are treated as being equivalent. If the name is not recognized or that option was not present, an empty list is returned.

For options found by the parser, the list will contain an entry for each time the option was encountered by the parser. If the option wasn't specified on the command line, the default values are returned.

An empty list is returned if the option does not take a value.

另請參閱 value (), QCommandLineOption::setDefaultValue (),和 QCommandLineOption::setDefaultValues ().

QStringList QCommandLineParser:: values (const QCommandLineOption & option ) const

這是重載函數。

Returns a list of option values found for the given option , or an empty list if not found.

For options found by the parser, the list will contain an entry for each time the option was encountered by the parser. If the option wasn't specified on the command line, the default values are returned.

An empty list is returned if the option does not take a value.

另請參閱 value (), QCommandLineOption::setDefaultValue (),和 QCommandLineOption::setDefaultValues ().