Validators in QT

Validators are the input restriction filters we can apply up on our input fields like QLineEdit. We can make validators and apply to them so that they can be made to accept only numbers, capital letters, etc..

QT have some predefined validators. Eg for int,Regular expression etc.

We can create our own validators by subclassing QValidator class.

Example: Validator for Digits 0-9

#include “QValidator.h”

//Derive from Qvalidator
class DigitValidator:public QValidator
{   

    //Validation function. Pure virtual in QValidator
    inline State validate( QString & input, int & pos ) const
    {

        //Create a regular expression for the condition
        QRegExp vRX;
        vRX.setPattern(“[^0-9]”);

       //Search for it in the input
        if(input.contains(vRX))
        {
            return QValidator::Invalid;
        }
        else
            return QValidator::Acceptable;
    }   
};

void main()
{
    QLineEdit *txtInPut;
    txtInPut->setValidator(new DigitValidator);
}

Now the txtInPut line edit  box will only accept the input if its 0-9 other characters cant be entered.

Advertisements