限制QLineEdit的数值输入范围

        在使用QLineEdit输入数值时,经常遇到限制其范围的需要,比如角太阳高度角范围为[-90,90],经度值范围[-180,180],方位角范围[0,360]。Qt提供了QIntValidator和QDoubleValidator可以限定数值输入范围,如使用QIntValidator限制整数的数值范围:
例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);
限制浮点数输入范围为[-180,180]
QRegExp rx("(^-?180$)|(^-?1[0-7]\\d$)|(^-?[1-9]\\d$)|(^-?[1-9]$)|^0$");
QRegExpValidator *pReg = new QRegExpValidator(rx, this);
lineEdit->setValidator(pReg);

限制浮点数输入范围为[-180,180]
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})?)$

 式子中开头的^和结尾的$限定字符串的开始和结尾;
 "-?" 表示一个或0个负号,这里面的问号表示其前面的字符重复0次或1次;
 管道符“|”表示平行分组,比如后三个,表示180或其它形式;
 [1-9] 表示限定数字范围为1到9,其余类似,如果是有限几个值,还可以用枚举的方式,比如限定-255到255时,第一个数字2的限定,应该表达为[1,2],这表示这个位置只允许是1或者2;
 "\d"是一个转义字符,表示匹配一位数字;
 “\.” 表示匹配小数点;
 "\d+",这里面的+表示其前面的\d重复一次或多次;
 "\d{1,4}",里面的{1,4}表示重复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)?)$
--------------------- 
作者:深蓝静音 
来源:CSDN 
原文:https://blog.csdn.net/giselite/article/details/12708031 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值