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.
Asked
Active
Viewed 9,918 times
2

cbuchart
- 10,847
- 9
- 53
- 93
-
4Not sure what you mean by writing, but are you looking for validation? See [QDoubleValidator](http://doc.qt.io/qt-5/qdoublevalidator.html) – Sep 23 '17 at 18:29
2 Answers
4
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.

cbuchart
- 10,847
- 9
- 53
- 93
-
2@mark1999 Instead of using a `QLineEdit` and a `QDoubleValidator`, you can also use a `QDoubleSpinBox`. It does a little more like allowing the user to step from a value to another using the mouse wheel. – Benjamin T Sep 25 '17 at 13:18
-
@BenjaminT +1. I agree too: a `QDoubleSpinBox` would be a nicer and cleaner solution if the OP can put aside the `QLineEdit`. – cbuchart Sep 26 '17 at 07:10
-1
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