如何设置输入掩码和QValidator到QLineEdit一次在Qt? [英] How to set Input Mask and QValidator to a QLineEdit at a time in Qt?

查看:217
本文介绍了如何设置输入掩码和QValidator到QLineEdit一次在Qt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个接受IP地址的行编辑。如果我给输入掩码:

I want a line edit which accepts an ip address. If I give input mask as:

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

它接受大于255的值。如果我给验证器,那么我们必须给一个点。)每三位数字后。

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?

推荐答案


它接受大于255的值。 / p>

It is accepting value greater than 255.

当然,因为'0'表示 this

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

使用regex

将输入拆分为四个条目,并自行验证每个条目,

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

正则表达式解决方案可能是快速的,但也是最难的IMHO:

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);

免责声明:这只会正确验证IP4地址,所以如果你需要未来。

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

这篇关于如何设置输入掩码和QValidator到QLineEdit一次在Qt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆