コマンドライン引数を扱う方法
Qt 5.2 で QCommandLineParser と QCommandLineOption というクラスが追加され、コマンドライン引数の扱いが大幅に簡単になりました。
シンプルな使い方
sl コマンドのオプションに倣って -a, -l, -F と -h/–help を解析してみます。
#include <QtCore/QCoreApplication>
#include <QtCore/QCommandLineParser>
#include <QtCore/QDebug>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
app.setApplicationName(QStringLiteral("sl - correct miss typing"));
QCommandLineParser parser;
parser.setApplicationDescription(QStringLiteral("sl is a highly developed animation program, which corrects your miss typing."));
parser.addHelpOption();
QCommandLineOption accidents(QStringLiteral("a"), QStringLiteral("It seems some accidents have happened. People give sad cries."));
parser.addOption(accidents);
QCommandLineOption smaller(QStringLiteral("l"), QStringLiteral("Becomes smaller."));
parser.addOption(smaller);
QCommandLineOption fly(QStringLiteral("F"), QStringLiteral("Flies."));
parser.addOption(fly);
parser.process(app);
if (parser.isSet(accidents)) {
qDebug() << "Help!";
}
if (parser.isSet(smaller)) {
qDebug() << "smaller";
}
if (parser.isSet(fly)) {
qDebug() << "I can fly!";
}
return 0;
}
実行
$ ./sl $ ./sl -a Help! $ ./sl -l smaller $ ./sl -a -l Help! smaller $ ./sl -al Help! smaller $ ./sl -h Usage: ./sl [options] sl is a highly developed animation program, which corrects your miss typing. Options: -h, --help Displays this help. -a It seems some accidents have happened. People give sad cries. -l Becomes smaller. -F Flies. $ ./sl -S Unknown option 'S'.
おわりに
色々なケースに対応できるような作りになっているので、詳細は QCommandLineParser と QCommandLineOption のドキュメントをご覧ください。
これ使い方合ってるの?という場合は、qtbase/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp のテストケースが参考になるかもしれません。