QLineEdit限制输入格式

使用正则表达式QRegExp,在Qt帮助文档中有详细使用说明。

1.限制普通输入

拿ip设置输入框为例:

在输入框所在界面构造函数中写入:

    QRegExp regExp("[0-9.]{1,15}");
    ui->lineEdit_ipv4_addr->setValidator(new QRegExpValidator(regExp,this));
    ui->lineEdit_ipv4_netmask->setValidator(new QRegExpValidator(regExp,this));

其中:

[0-9.]表示只允许0-9之间的数字和特殊符号.的输入,如果需要限制字母,则改为[a-zA-Z]即可。

{1,15}表示匹配1次,并且最多允许输入15个元素。

2.按照一定的格式限制输入

还是拿ip输入框为例:

要求输入类似192.168.1.1这种ip地址,并且点不用自己输入,直接显示在输入框,输入3个数字后自动跳转点后面继续输入:

QString ipRangeStr = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";//限制最大输入255
QRegExp ipRegex ("^" + ipRangeStr 
                      + "\\." + ipRangeStr 
                      + "\\." + ipRangeStr 
                      + "\\." + ipRangeStr + "$");
auto ipValidator = new QRegExpValidator(ipRegex,this);//检查其有效性
ui->lineEdit_ipv4_addr->setValidator(ipValidator);
ui->lineEdit_ipv4_addr->setInputMask("000.000.000.000");

更多用法:


Character	Meaning
A
 
ASCII alphabetic character required. A-Z, a-z.
 
a
 
ASCII alphabetic character permitted but not required.
 
N
 
ASCII alphanumeric character required. A-Z, a-z, 0-9.
 
n
 
ASCII alphanumeric character permitted but not required.
 
X
 
Any character required.
 
x
 
Any character permitted but not required.
 
9
 
ASCII digit required. 0-9.
 
0
 
ASCII digit permitted but not required.
 
D
 
ASCII digit required. 1-9.
 
d
 
ASCII digit permitted but not required (1-9).
 
#
 
ASCII digit or plus/minus sign permitted but not required.
 
H
 
Hexadecimal character required. A-F, a-f, 0-9.
 
h
 
Hexadecimal character permitted but not required.
 
B
 
Binary character required. 0-1.
 
b
 
Binary character permitted but not required.
 
>
 
All following alphabetic characters are uppercased.
 
<
 
All following alphabetic characters are lowercased.
 
!
 
Switch off case conversion.
 
\
 
Use \ to escape the special characters listed above to use them as separators.

只需在双引号中标明要用的格式

“000.000.000.000;”是一个IP地址
“HH:HH:HH:HH:HH:HH;0”是一个MAC地址。
“\\0\\xHHHH;0”是只允许输入一个16位的十六进制数。

 

你可能感兴趣的:(Qt)