[Solved] Using QRegExp with QLineEdit



  • Hello -

    I am would like to use a QRegExp on a QLineEdit. I haven't used regular expressions before, but have read a number of tutorials. I am unable to get the behavior I am trying to acheive.

    I would like to be able to enter uppercase and lowercase letters, as well as digits. At least one character must be entered, but no more than 8. The following is the code I have:

    @
    QRegExp rx ("[A-Za-z0-9]{1,8}");
    lineEdit->setValidator (new QRegExpValidator (rx, this));

    if (lineEdit->hasAcceptableInput ()) {
    buttonBox->button (QDialogButtonBox::Ok)->setEnabled (true);
    } else {
    buttonBox->button (QDialogButtonBox::Ok)->setEnabled (false);
    }
    @

    I am unable to enter any characters after I enter the 8th one and I am unable to enter any characters that are not allowed in the QLineEdit. For example, if I enter 'abcdefghi' only 'abcdefgh' shows up in the QLineEdit and OK remains enabled. I would like for the i to show up, but then for OK to become disabled. Likewise, if I type in 'abcd$efgh' only 'abcdefgh' shows up when I would like for all entered characters to show up and, if it is not acceptable input, for the OK button to become disabled. Is this behavior achievable and, if so, how?

    Thanks,
    Kate



  • Hi Kate,

    the validator ensures, that no invalid input can be entered.
    If you want to achieve this behavior, you ahve to do it outside, without a validator.



  • As long as QRegExp rx ("[A-Za-z0-9]{1,8}"); is set {1,8} you will not be able to input more characters.
    Here is what the code should look like if I didn't misunderstood you:
    @QRegExp rx ("[A-Za-z0-9]");
    lineEdit->setValidator (new QRegExpValidator (rx, this));

    if ((lineEdit->hasAcceptableInput ())&&lineEdit->text().length()<9) {
    buttonBox->button (QDialogButtonBox::Ok)->setEnabled (true);
    } else {
    buttonBox->button (QDialogButtonBox::Ok)->setEnabled (false);
    }@
    I didn't compile it but you should understand my idea with it.



  • Super - thanks for the replies and the explanations.

    Kate



  • This only does part of it.
    if you type ‘abcd$efgh’ only ‘abcdefgh’ will show up, which was also not liked.

    you could go that way:

    @
    // remove this to enable all characters input: lineEdit->setValidator (new QRegExpValidator (rx, this));

    QRegExp rx ("[A-Za-z0-9]{1,8}");
    if (rx.exactMatch(lineEdit->text())) 
    {
        buttonBox->button (QDialogButtonBox::Ok)->setEnabled (true);
    } 
    else 
    {
        buttonBox->button (QDialogButtonBox::Ok)->setEnabled (false);
    }
    

    @

    The code was hacked directly to devnet


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.