QLineEdit限制数值输入范围

本文阅读 3 分钟
首页 应用开发 正文

1 引言

在使用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,下面是一些常用的利用正则表达式校验器限定数值范围的用法

2 使用方式

2.1 限制浮点数输入范围为[-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);  

2.2 限制浮点数输入范围为[-180,180]

QRegExp rx("(^-?180$)|(^-?1[0-7]\\d$)|(^-?[1-9]\\d$)|(^-?[1-9]$)|^0$");  
QRegExpValidator *pReg = new QRegExpValidator(rx, this);  
lineEdit->setValidator(pReg);  

2.3限制浮点数输入范围为[-180,180]

QRegExp rx("^-?(180|1?[0-7]?\\d(\\.\\d+)?)$");  
QRegExpValidator *pReg = new QRegExpValidator(rx, this);  
lineEdit->setValidator(pReg);  

2.4限制浮点数输入范围为[-180,180]并限定为小数位后4位

QRegExp rx("^-?(180|1?[0-7]?\\d(\\.\\d{1,4})?)$");  
QRegExpValidator *pReg = new QRegExpValidator(rx, this);  
lineEdit->setValidator(pReg);  

2.5 限制浮点数输入范围为[-90,90]并限定为小数位后4位

QRegExp rx("^-?(90|[1-8]?\\d(\\.\\d{1,4})?)$");  
QRegExpValidator *pReg = new QRegExpValidator(rx, this);  
lineEdit->setValidator(pReg);  

3 正则表达式:

  • "^" 限定字符串的开始
  • "$" 限定字符串的结尾
  • "-?" 表示一个或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)?)$
本文来自投稿,不代表本站立场,如若转载,请注明出处:
QtWebEngine跨域问题解决方案
« 上一篇 02-28
Qt表格(QTableWidget)中复选框(QCheckBox)的使用
下一篇 » 03-09