コマンドラインの引数を得る方法その2。QCommandLineParserクラスを使う。
環境:QT5.5
リンク
http://doc.qt.io/qt-5/qcoreapplication.html
http://doc.qt.io/qt-5/qstring.html
http://doc.qt.io/qt-5/qcommandlineparser.html#addHelpOption
http://doc.qt.io/qt-5/qcommandlineoption.html#QCommandLineOption-1
インクルードファイル
#include
#include
#include
コード
QCoreApplication a(argc, argv);
//*** Set Command Option
QCommandLineParser parser;
// 引数に -xxx などのロングワードを使う場合は設定
parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
// ヘルプを出力したい場合 -h でヘルプ表示
parser.addHelpOption();
// -all オプション
QCommandLineOption exportAll("all", "全ファイルを圧縮");
parser.addOption(exportAll);
// -f [file] オプション
QCommandLineOption exportFile("f", "指定されたファイルを圧縮", "file");
parser.addOption(exportFile);
// -a 2026/02/11 オプション ファイルの更新日付で絞込む
QCommandLineOption dateAfter("a", "指定日付以降のデータが処理対象", "date");
parser.addOption(dateAfter);
// -b 2026/02/11 オプション ファイルの更新日付で絞込む
QCommandLineOption dateBefore("b", "指定日付以前のデータが処理対象", "date");
parser.addOption(dateBefore);
// 引数のチェック
if ( !parser.parse(QCoreApplication::arguments())) {
// エラー
return false;
}
parser.process(a);
QString expfile;
// 指定された引数に対応する処理
if ( parser.isSet(exportAll) ) {
// -all が指定された場合の処理
} else if ( parser.isSet(exportFile) ) {
// -f が指定された場合の処理
QString file = parser.value(exportFile); // ファイル名を取得
} else if ( parser.isSet(dateAfter) ) {
// -a が指定された場合の処理
QString date = parser.value(dateAfter); // 日付を取得
} else if ( parser.isSet(dateBefore) ) {
// -b が指定された場合の処理
QString date = parser.value(dateBefore); // 日付を取得
}
コメント