简体   繁体   中英

Write only float values in QLineEdit

How to write in QLineEdit float numbers in range (0.0 - 5.0)? I use qregexp for such a task for example QRegExp a("([a-zA-Z]{3,30})") to write user name but have no ideas to write float numbers.

The best option is to use the QDoubleValidator for such task, since it will not only validate the shape of the input but also the range :

auto dv = new QDoubleValidator(0.0, 5.0, 2); // [0, 5] with 2 decimals of precision
yourLineEdit->setValidator(dv);

If you are dealing with many decimals (or if you plan to change the range to a wider one), you'd probably be interested in disabling the scientific notation:

dv->setNotation(QDoubleValidator::StandardNotation);

On the other hand, and for completeness of the answer since you asked for regular expressions, a general regex for float number is [-+]?[0-9]*\\.?[0-9]+ , so for your particular range you can try: ([0-4]?\\.[0-9]+)|(5\\.0+)|([0-5]) . Anyway, I recommend using the validator, since the regex is more difficult to scale if range changes through the project or in run-time.

Using a regex and breaking up the ranges, 0.0 - 5.0 would be :

[0-4]\\.\\d|5\\.0

Expanded

   #  0.0  to  4.9
   [0-4] \. \d 
|  
   #  5.0
   5 \. 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM