Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

SetValidator doesn't work



  • I wrote:
    ui->lineEdit->setValidator(new QIntValidator(-30,+30,this));
    It works only for numbers <-30 but it doesn't work for numbers>30



  • This post is deleted!

  • Lifetime Qt Champion

    Hi,

    What exactly do you mean by but it doesn't work for numbers>30 ?



  • @SGaist it doesn't permit to write numbers <-30 but it permits to write in LineEdit numbers>30


  • Lifetime Qt Champion

    @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));
    
    
     }

  • Lifetime Qt Champion

    @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));
    
    
     }
    


  • @mrjj it's an error, it isn't necessary


Log in to reply