例1:
lineEdit->setValidator(new QIntValidator(0, 1000, this));例2:
lineEdit->setValidator(new QDoubleValidator(-180.0,180.0,6,this));
对于浮点数,使用QDoubleValidator时,发现只能限制只输入小数,但是无法设定数值范围,因此有必要对这个问题做一番研究。
除了QIntValidator和QDoubleValidator,Qt提供另一种校验器是正则表达式校验器:QRegExpValidator,下面是一些常用的利用正则表达式校验器限定数值范围的用法:
限制浮点数输入范围为[-999999.9999,999999.9999]
QRegExp rx("^(-?[0]|-?[1-9][0-9]{0,5})(?:\\.\\d{1,4})?$|(^\\t?$)"); QRegExpValidator *pReg = new QRegExpValidator(rx, this); lineEdit->setValidator(pReg);
QRegExp rx("(^-?180$)|(^-?1[0-7]\\d$)|(^-?[1-9]\\d$)|(^-?[1-9]$)|^0$"); QRegExpValidator *pReg = new QRegExpValidator(rx, this); lineEdit->setValidator(pReg);
QRegExp rx("^-?(180|1?[0-7]?\\d(\\.\\d+)?)$"); QRegExpValidator *pReg = new QRegExpValidator(rx, this); lineEdit->setValidator(pReg);限制浮点数输入范围为[-180,180]并限定为小数位后4位
QRegExp rx("^-?(180|1?[0-7]?\\d(\\.\\d{1,4})?)$"); QRegExpValidator *pReg = new QRegExpValidator(rx, this); lineEdit->setValidator(pReg);限制浮点数输入范围为[-90,90]并限定为小数位后4位
QRegExp rx("^-?(90|[1-8]?\\d(\\.\\d{1,4})?)$"); QRegExpValidator *pReg = new QRegExpValidator(rx, this); lineEdit->setValidator(pReg);
简单说明一下这几个正则表达式:
^(-?[0]|-?[1-9][0-9]{0,5})(?:\.\d{1,4})?$|(^\t?$)
(^-?180$)|(^-?1[0-7]\d$)|(^-?[1-9]\d$)|(^-?[1-9]$)|^0$
^-?(180|1?[0-7]?\d(\.\d+)?)$
^-?(180|1?[0-7]?\d(\.\d{1,4})?)$
^-?(90|[1-8]?\d(\.\d{1,4})?)$
有了以上知识,下面我们可以很快的写出限定[-255,255]的正则表达式:
[-255,255]整数:^-?(255|[1,2]?[0-4]?\d|[1,2]?5[0-4]?)$
[-255,255]小数:^-?(255|([1,2]?[0-4]?\d|[1,2]?5[0-4]?)(\.\d)?)$
参考:
[1]Qt限制文本框输入的方法
[2]怎么让QLineEdit中只能输入数字
[3]用正则表达式配出-180到180该怎么写
[4]求正则表达式,在-180到180之间的数字,包括浮点数