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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s