How to set Input Mask and QValidator to a QLineEdit at a time in Qt?

后端 未结 5 1400
一生所求
一生所求 2020-12-31 21:14

I want a line edit which accepts an ip address. If I give input mask as:

ui->lineEdit->setInputMask(\"000.000.000.000\");

It is accep

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 21:21

    For those who wonder about the following hint in the QT doku:

    To get range control (e.g., for an IP address) use masks together with validators.

    In this case the validator needs to take care of blanks. My solution, adapted from lpapp's answer and this Qt forum post, therefore reads:

    QString ipRange = "(([ 0]+)|([ 0]*[0-9] *)|([0-9][0-9] )|([ 0][0-9][0-9])|(1[0-9][0-9])|([2][0-4][0-9])|(25[0-5]))";
    // You may want to use QRegularExpression for new code with Qt 5 (not mandatory).
    QRegExp ipRegex ("^" + ipRange
                     + "\\." + ipRange
                     + "\\." + ipRange
                     + "\\." + ipRange + "$");
    QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
    lineEdit->setValidator(ipValidator);
    lineEdit->setInputMask("000.000.000.000");
    // Avoid having to move cursor before typing
    linEdit->setCursorPosition(0);
    

    I am a beginner at using regular expressions, so feel free to recommend improvements.

提交回复
热议问题