Allow entry in QLineEdit only within range of QDoubleValidator

前端 未结 7 732
傲寒
傲寒 2020-12-16 05:52

I have a set of QLineEdits that are supposed to accept double values within a certain range, (e.g., -15 to 15).

I have something along these lines when

7条回答
  •  眼角桃花
    2020-12-16 06:23

    It is possible to do this also without subclassing.

    lineEdit = new QLineEdit();
    connect(lineEdit,SIGNAL(textChanged(QString)), this, SLOT(textChangedSlot(QString)));
    
    QDoubleValidator *dblVal = new QDoubleValidator(minVal, maxVal, 1000, lineEdit);
    dblVal->setNotation(QDoubleValidator::StandardNotation);
    dblVal->setLocale(QLocale::C);
    lineEdit->setValidator(dblVal);
    

    Setting of the locale may be important because it defines which characters are interpreted as a decimal separator. Format of the input string defines which locales should be used.

    In the textChangedSlot, we can validate input this way:

    QString str = lineEdit->text();
    int i = 0;
    QDoubleValidator *val = (QDoubleValidator *) lineEdit->validator();
    QValidator::State st = val->validate(str, i);
    
    if (st == QValidator::Acceptable) {
        // Validation OK
    } else {
        // Validation NOK
    }
    

    In this case also QValidator::Intermediate state is interpreted as a failed case.

    If we connect textChanged -signal to the textChangedSlot, validation is done after every input field change. We could also connect editingFinished() or returnPressed() -signals to the validation slot. In that case, validation is done only when user stops editing the string.

提交回复
热议问题