SetValidator doesn't work
Solved
General and Desktop
-
I wrote:
ui->lineEdit->setValidator(new QIntValidator(-30,+30,this));
It works only for numbers <-30 but it doesn't work for numbers>30 -
Hi,
What exactly do you mean by
but it doesn't work for numbers>30
? -
@vale88
Hi
From I understand, QIntValidator returns QValidator::Intermediate for when the value is outside the limit
and QLineEdit accepts that.
You can try to use a custom validator
like
ui->lineEdit->setValidator(new MyIntRangeValidator(-30,30,this));class MyIntRangeValidator : public QIntValidator { public: MyIntRangeValidator(int bottom, int top, QObject *parent) : QIntValidator(bottom, top, parent) { } QValidator::State validate(QString &s, int &) const override { if (s.isEmpty() || s == "-") { return QValidator::Intermediate; } bool ok; int d = s.toInt(&ok); if (ok && d >= bottom() && d <= top() ) { return QValidator::Acceptable; } else { return QValidator::Invalid; } } };
Which works more like expected.
-
@mrjj I solved in a more simple way:
void MainWindow::on_Value_textChanged(const QString &arg1)
{//se i valori immessi non sono nel range impedisco di poterli scrivere if(arg1.toInt()>30 || arg1.toInt()<-30) { //se ad esempio cerchero di scrivere 40 scriverò 4 int arg2 = arg1.toInt()/10; ui->Value->setText(QString::number(arg2)); }
-
@vale88
Indeed it is :) , but would be a bit messy if u needed various LineEdits with slightly different
ranges.
However, why call toInt() so many times?void MainWindow::on_Value_textChanged(const QString &arg1) { //se i valori immessi non sono nel range impedisco di poterli scrivere int value = arg1.toInt(); if(value>30 || value<-30) { //se ad esempio cerchero di scrivere 40 scriverò 4 ui->Value->setText(QString::number(value/10)); }