Prevent user from typing invalid values in QLineEdit
-
I'm trying to to use QDoubleValidator to prevent user from typing invalid values, or values which are out of range, in QLineEdit.
Im not sure if validators suppose to block entering wrong values while typing or only when the user press "Enter" or release focus.
(docu says: ...The user may change the content to any Intermediate value during editing, but will be prevented from editing the text to a value that v validates as Invalid. ..)
I need a solution which prevents the user from typing any invalid values.
I tried something like this:_validator(new QDoubleValidator(0.0, 10.0, 5, this)) _validator->setNotation(QDoubleValidator::StandardNotation); _validator->setLocale(QLocale::C); setValidator(_validator);
But i can still enter numbers up to 99.
Decimal check seems to work and hasAcceptableInput() works also correctly.
It returns false for values higher than 10.0, when i add signal/slot connection for textChanged(). -
@wakiki said in Prevent user from typing invalid values in QLineEdit:
I would rather avoid changing the widget type, but i will check that.
Odd. Why do you want a
QLineEdit
for editing a number when it is not designed for that,QDoubleSpinBox
is and has range validation built into it?Is it possible to show a string in QDoubleSpinBox? I want to add something like ".sec" behind the number.
How do you do this at present with a
QLineEdit
which has aQDoubleValidator
? If the user types in.sec
it won't validate as a number? Or do you mean you put.sec
somewhere outside the widget (e.g. in aQLabel
), in which case it does not affect which widget you use? Or,QDoubleSpinBox
has an optionalprefix
/suffix
, is that what you are wanting for your.sec
?Meanwhile, QDoubleValidator::validate() says
Returns
Intermediate
if input contains a double that is outside the range or is in the wrong format; e.g. is empty.so I am guessing that is what you get when you enter
99
. -
Currently my QLineEdit has no validator at all. Its handled after editing is finished. I guess you are right,
QDoubleSpinBox with a suffix would be the best solution in this case.We used QLineEdit for all editable double parameters so far. I don't know why, but live typing validation was not a required feature,
so i will stick with QLineEdit. -
@wakiki
Fair enough. I think you will find the validator prevents the user from typing some things --- for example invalid characters or a string which is too long --- but it won't for example prevent things being typed which could be changed or adjusted to be right. I'm not sure what the rules are. It will just returnIntermediate
for the verification.