Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 accepting values greater than 255. If I give a validator then we have to give a dot(.) after every three digits. What would the best way to handle it?

like image 688
QtUser Avatar asked Apr 19 '14 05:04

QtUser


2 Answers

It is accepting value greater than 255.

Absolutely, because '0' means this:

ASCII digit permitted but not required.

As you can see, this is not your cup of tea. There are at least the following ways to circumvent it:

  • Write a custom validator

  • Use regex

  • Split the input into four entries and validate each entry on its own while still having visual delimiters between the entries.

The regex solution would be probably the quick, but also ugliest IMHO:

QString ipRange = "(?:[0-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);

Disclaimer: this will only validate IP4 addresses properly, so it will not work for IP6 should you need that in the future.

like image 66
lpapp Avatar answered Sep 21 '22 09:09

lpapp


The easier method is try inputmask option

ui->lineEdit_IP->setInputMask( "000.000.000.000" );

and in your validation code use the following simple condition

QHostAddress myIP;
   if( myIP.setAddress( ui->lineEdit_IP->text()) )
   qDebug()<<"Valid IP Address";
   else
   qDebug()<<"Invalid IP address";
like image 27
Arun Kumar K S Avatar answered Sep 21 '22 09:09

Arun Kumar K S