Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write only float values in QLineEdit

Tags:

c++

qt

qregexp

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.


1 Answers

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.

like image 55
cbuchart Avatar answered Jun 14 '26 03:06

cbuchart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!