Qt4的命令行解析器

elc*_*uco 24 command-line parsing qt4

我正在寻找Qt4的命令行解析器.

我做了一个小的谷歌搜索,发现了这个:http://www.froglogic.com/pg?id = PublicublicFreeware&category = memopt然而它缺乏对"--enable-foo"和"--disable-foo"开关的支持.除此之外,它看起来像一个真正的赢家.

编辑:

似乎Frologic取消了这个.所以我看到的最佳选择是使用Boost(不是API也不是ABI稳定)或者支持kdelibs.好极了...

eph*_*ent 23

QCoreApplication的构造函数需要(int &argc, char **argv)(并QApplication继承自QCoreApplication).正如文档所述,强烈建议

由于QApplication的也与常见的命令行参数的交易,它通常是一个好主意,创建它之前的任何解释或修改argv应用程序本身来完成.

如果你让Qt在处理论证时获得第一遍,那么使用QStringList QCoreApplication::arguments()而不是走路也是一个好主意argv; QApplication可能会删除它为自己使用的一些论据.

这不适合与其他参数解析库非常兼容......

但是,kdelibs确实带有一个很好的参数解析器,KCmdLineArgs.它是LGPL,KApplication如果你真的想要(呼叫KCmdLineArgs::init)可以使用.

KCmdLineOptions options;
options.add("enable-foo", ki18n("enables foo"));
options.add("nodisable-foo", ki18n("disables foo"));
// double negatives are confusing, but this makes disable-foo enabled by default

KCmdLineArgs::addCmdLineOptions(options);
KApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

if (args->isSet("enable-foo") && !args->isSet("disable-foo"))
    cout << "foo enabled" << endl;
else
    cout << "foo disabled" << endl;
Run Code Online (Sandbox Code Playgroud)

未经测试(曾经测试过他们在SO上发布的内容?).

  • 扯掉kdelibs ......真是个好主意,我怎么没想到呢?我将不得不测试这个! (3认同)

Dav*_*ure 17

从Qt 5.2开始,你终于可以在QtCore中找到一个解决方案:我那里贡献了QCommandLineParser.


Joh*_*han 9

这或多或少与ephemient相同,但有一个简单的正则表达式来帮助解析args.(如果你只需要一些args,这种方式可能很有用)

用这个运行:

./QArgTest --pid=45 --enable-foo
Run Code Online (Sandbox Code Playgroud)

和代码:

int main(int argc, char *argv[]) {
    QApplication app(argc, argv, false);
    qDebug() << "QApp arg test app"; 

    QStringList args = app.arguments();

    int pid = 0;

    QRegExp rxArgPid("--pid=([0-9]{1,})");
    QRegExp rxArgFooEna("--enable-foo");
    QRegExp rxArgFooDis("--disable-foo");

    for (int i = 1; i < args.size(); ++i) {
        if (rxArgPid.indexIn(args.at(i)) != -1 ) {   
            pid =  rxArgPid.cap(1).toInt();
            qDebug() << i << ":" << args.at(i) << rxArgPid.cap(1) << pid;
        }
        else if (rxArgFooEna.indexIn(args.at(i)) != -1 ) {   
            qDebug() << i << ":" << args.at(i) << "Enable Foo";
        } 
        else if (rxArgFooDis.indexIn(args.at(i)) != -1 ) {   
            qDebug() << i << ":" << args.at(i) << "Disable Foo";
        } 
        else {
            qDebug() << "Uknown arg:" << args.at(i);
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 7

还有来自http://www.libqxt.org/的 QxtCommandOptions