Qt QLineEdit Input Validation

*爱你&永不变心* 提交于 2021-02-05 06:52:30

问题


How would one set an input validator on a QLineEdit such that it restricts it to a valid IP address? i.e. x.x.x.x where x must be between 0 and 255.and x can not be empty


回答1:


You are looking for QRegExp and QValidator, to validate an IPv4 use this expresion:

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-‌​9]|[01]?[0-9][0-9]?)‌​\.(25[0-5]|2[0-4][0-‌​9]|[01]?[0-9][0-9]?)‌​\.(25[0-5]|2[0-4][0-‌​9]|[01]?[0-9][0-9]?)‌​\b

Example:

QRegExp ipREX("\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-‌​9]|[01]?[0-9][0-9]?)‌​\.(25[0-5]|2[0-4][0-‌​9]|[01]?[0-9][0-9]?)‌​\.(25[0-5]|2[0-4][0-‌​9]|[01]?[0-9][0-9]?)‌​\b");
ipREX.setCaseSensitivity(Qt::CaseInsensitive);
ipREX.setPatternSyntax(QRegExp::RegExp);

Now, use it as validator of your text lineedit:

QRegExpValidator regValidator( rx, 0 );
ui->lineEdit->setValidator( &regValidator );

Now, just read your input and the validator will validate it =). If you want to do it manually, try something like this:

ui->lineEdit->setText( "000.000.000.000" );
const QString input = ui->lineEdit->text();
// To check if the text is valid:
qDebug() << "IP validation: " << myREX.exactMatch(input);

There is another way to made it using Qt classes, QHostAddress and QAbstractSocket:

QHostAddress address(input);
if (QAbstractSocket::IPv4Protocol == address.protocol())
{
   qDebug("Valid IPv4 address.");
}
else if (QAbstractSocket::IPv6Protocol == address.protocol())
{
   qDebug("Valid IPv6 address.");
}
else
{
   qDebug("Unknown or invalid address.");
}



回答2:


The answer is here

In short: You have to set QRegExpValidator with the appropriate Regular Expression for IP4 adresses.



来源:https://stackoverflow.com/questions/39202697/qt-qlineedit-input-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!