Qt validator doesnt work like described in docs
-
QIntValidator
from docs:QValidator *validator = new QIntValidator(100, 999, this); QLineEdit *edit = new QLineEdit(this); // the edit lineedit will only accept integers between 100 and 999 edit->setValidator(validator);
What I am using in my code:
ui->lineEdit->setValidator(new QIntValidator(1,1000,this));
I was expecting that i can input this lineEdit between 1 to 1000 but i can input from 0 to 9999. Any idea why?
-
@masa4 The validator work exactly as in the docs. Read examples in the documentation following you one you quoted, and the paragraph following:
Notice that the value 999 returns Intermediate. Values consisting of a number of digits equal to or less than the max value are considered intermediate. This is intended because the digit that prevents a number from being in range is not necessarily the last digit typed. This also means that an intermediate number can have leading zeros.
For your validator, with 9999 typed into the line edit, QLineEdit::hasAcceptableInput() will return false, and QValidator::validate() will return QValidator::Intermediate.
#include <QApplication> #include <QDebug> #include <QLineEdit> #include <QIntValidator> int main(int argc, char **argv) { QApplication app(argc, argv); QString test("9999"); QLineEdit edit; QIntValidator *validator = new QIntValidator(1, 1000, &edit); edit.setValidator(validator); edit.setText(test); int pos; qDebug() << validator->validate(test, pos); qDebug() << edit.hasAcceptableInput(); return app.exec(); }
-
@ChrisW67 I want to prevent user to input anyting outside the 1-1000. User should not eligible to input enter 0, or anything bigger to 1000 and negative values. Right now user can't input negative but can input 0 and numbers that bigger than 1000.