Command line parser for Qt4

前端 未结 11 1763
离开以前
离开以前 2021-01-30 23:23

I am looking for a command line parser for Qt4.

I did a small google search, and found this: http://www.froglogic.com/pg?id=PublicationsFreeware&category=getopt how

11条回答
  •  星月不相逢
    2021-01-30 23:32

    It's 2013 and still no "1st party" arg parser. Anyways..if anyone finds themselves facing the same problem and would like to avoid the learning curves that come with cmd parser libs, here is a "quick & dirty" fix for you:-

    QString QArgByKey(QString key, QChar sep = QChar('\0') ) //prototype usually in separate header
    
    QString QArgByKey(QString key, QChar sep )
    {
        bool sepd=sep!=QChar('\0');
        int pos=sepd?qApp->arguments().indexOf(QRegExp('^'+key+sep+"\\S*")):qApp->arguments().indexOf(QRegExp(key));
        return pos==-1?QString::null:
        (sepd?qApp->arguments().at(pos).split(sep).at(1):(++posarguments().size()?qApp->arguments().at(pos):QString::null));
    }
    

    Example:-

    user@box:~$ ./myApp  firstKey=Value1 --secondKey Value2 thirdKey=val3.1,val3.2,val3.3 --enable-foo
    

    Usage:

    QString param1   = QArgByKey("firstkey",'='); // Returns `Value1` from first pair
    QString param2   = QArgByKey("--secondkey"); // Returns `Value2` from second pair
    QString param3-1 = QArgByKey("thirdkey",'=').split(',').at(0); // Returns `val3.1`
    bool fooEnabled  = qApp->arguments().contains("--enable-foo"); //To check for `--enable-foo` 
    

    Params can be passed in any order

    Edit: Updates to this snippet will be found here

提交回复
热议问题