Allow entry in QLineEdit only within range of QDoubleValidator

前端 未结 7 746
傲寒
傲寒 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:25

    That's because QDoubleValidator returns QValidator::Intermediate if the value is outside the bounds and QLineEdit accepts QValidator::Intermediate values.

    To implement the behavior you want you can make your own QDoubleValidator subclass like this:

    class MyValidator : public QDoubleValidator
    {
    public:
        MyValidator(double bottom, double top, int decimals, QObject * parent) :
            QDoubleValidator(bottom, top, decimals, parent)
        {
        }
    
        QValidator::State validate(QString &s, int &i) const
        {
            if (s.isEmpty()) {
                return QValidator::Intermediate;
            }
    
            bool ok;
            double d = s.toDouble(&ok);
    
            if (ok && d > 0 && d < 15) {
                return QValidator::Acceptable;
            } else {
                return QValidator::Invalid;
            }
        }
    };
    

    UPDATE: This will solve the negative sign issue, and also will accept locale double formats:

    class MyValidator : public QDoubleValidator
    {
    public:
        MyValidator(double bottom, double top, int decimals, QObject * parent) :
            QDoubleValidator(bottom, top, decimals, parent)
        {
        }
    
        QValidator::State validate(QString &s, int &i) const
        {
            if (s.isEmpty() || s == "-") {
                return QValidator::Intermediate;
            }
    
            QChar decimalPoint = locale().decimalPoint();
    
            if(s.indexOf(decimalPoint) != -1) {
                int charsAfterPoint = s.length() - s.indexOf(decimalPoint) - 1;
    
                if (charsAfterPoint > decimals()) {
                    return QValidator::Invalid;
                }
            }
    
            bool ok;
            double d = locale().toDouble(s, &ok);
    
            if (ok && d >= bottom() && d <= top()) {
                return QValidator::Acceptable;
            } else {
                return QValidator::Invalid;
            }
        }
    };
    

提交回复
热议问题