Search code examples
c++regexqtvalidationqregexp

QRegExpValidator maximum value


I would like to use QRegExpValidator in order to force user to: - type in values only from a certain range (double type), - the double type should be typed in using dot not coma - no other formats are allowed

So far I have:

QRegExpValidator* rxv = new QRegExpValidator(QRegExp("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"), this);

This validator forces user to type in only double values with dot. I Dont know however, how to prevent user from typing in values out of range (for example range would be from 0 to 100.0). I Would aprichiate all help.


Solution

  • You can write your own validator, derived from QValidator. All you need is to implement virtual State validate(QString &input, int &pos) const = 0.

    UPDATE

    Example:

    MyValidator.h:

    class MyValidator : public QValidator
    {
        Q_OBJECT
    public:
        MyValidator(double min, double max, QObject *parent = 0);
    
        State validate(QString &input, int &pos) const;
    
    private:
        QRegExp mRexp;
        double mMin;
        double mMax;
    };
    

    MyValidator.cpp:

    MyValidator::MyValidator(double min, double max, QObject *parent) :
        QValidator(parent)
      , mRexp("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")
      , mMin(min)
      , mMax(max)
    {}
    
    QValidator::State MyValidator::validate(QString &input, int &pos) const
    {
        if (input.isEmpty())
            return Acceptable;
        if (!mRexp.exactMatch(input))
            return Invalid;
        const double val = input.toDouble();
        if (mMin <= val && val <= mMax)
            return Acceptable;
        return Intermediate;
    }