Qtの設定 - コマンドライン引数
概要
Qt 5.2以降では、QCommandLineParserクラスとQCommandLineOptionクラスが追加され、コマンドライン引数の扱いが簡潔になっている。
ここでは、これらのクラスの使用方法について記載する。
また、デバッグの時にのみ使用するコマンドライン引数の設定方法も記載する。
サンプルコード 1
以下のサンプルコードでは、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 ./sl -l ./sl -a -l ./sl -al ./sl -h ./sl -S # 結果 Help! smaller Help! smaller Help! smaller 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. Unknown option 'S'.
※備考
様々なケースに対応できるような構造になっている。
詳細は、QCommandLineParserとQCommandLineOptionのドキュメントを参照すること。
また、他の使用方法については、qtbase/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cppのテストケースを参照すること。
サンプルコード 2
上記とは別の方法として、QCoreApplication::arguments()を使用することもできる。
QCoreApplication::arguments()の型はQStringListであるため、簡単に取得および加工することができる。
以下の3つの例では、全てのコマンドライン引数をQStringListクラスで取得して表示している。
コマンドライン引数の1つ目の要素を削除している理由は、1つ目の引数にはソフトウェアのパスが渡されるからである。
 // 方法 1
 QStringList argv = QCoreApplication::arguments();
 
 argv.removeAt(0);
 
 for(QString arg : argv)
 {
    qDebug() << "argument = " << arg;
 }
 // 方法 2
 QStringList argv = QCoreApplication::arguments();
 
 for(int i = 1; i < arguments.count(); i++)
 {
    qDebug() << "argument = " << arguments.at(i);
 }
 // 方法 3
 QStringList argv = QCoreApplication::arguments();
  
 argv.removeAt(0);
 foreach(QString const &arg, arguments)
 {
    qDebug() << arg;
 }
デバッグ時のコマンドライン引数の設定
Qt Creatorを起動して、任意のQtプロジェクトを開く。
Qt Creatorの画面左にある[プロジェクト]アイコン - [Build & Run]セクション - [Run]項目を選択して、[実行時の設定]画面を表示する。
[実行時の設定]画面から、[実行]セクション - [コマンドライン引数]項目に、コマンドライン引数を記述する。
コマンドライン引数の記述方法は、以下の通りである。
# 各引数は半角スペースで区切る hoge piyo fuga # 引数の内容に空白が入っている場合は、ダブルクォーテーション""で囲む "hoge piyo" fuga # 引数の内容にダブルクォーテーション""が入っている場合は、直前にエスケープシーケンスを記述する "hoge \" piyo" fuga