开发者

QValidator in Qt?

开发者 https://www.devze.com 2023-04-05 15:02 出处:网络
I am validating my TextBox to take only numbers between 1-75. I am able to do this by using below code :

I am validating my TextBox to take only numbers between 1-75. I am able to do this by using below code :

QValidator *validator = new QIntValidator(1, 75, this);
QLineEdit *edit = new QLineEdit(this);
edit->setValidator(validator);

But now开发者_如何转开发 the problem is it takes zero also. I want to avoid Zero Any help is appreciated.


You are not currently validating: when you set a QValidator you are just filtering characters to those which could compose a valid input.

In order to do the actual validation, you have to check that QLineEdit::hasAcceptableInput() returns true.

For example, in a slot connected to the textChanged() signal, you could, depending on the value of the acceptableInput property, enable/disable the button submitting the data, preventing the user to go further with an invalid value, and/or change the text color (red for invalid).

For numerical values, you can also use a QSpinBox instead of QLineEdit. You can define its range (min/max), and its behavior if the value is not valid when the editing finishes (with QSpinBox::setCorrectionMode).


you can write your validator like that:

 class lvalidator : public QValidator
    {
        Q_OBJECT
    public:
        explicit lvalidator(QObject *parent = 0);
        virtual State validate ( QString & input, int & pos ) const
        {
            if (input.isEmpty())
                return Acceptable;

            bool b;
            int val = input.toInt(&b);

            if ((b == true) && (val > 0) && (val < 76))
            {
                return Acceptable;
            }
            return Invalid;
        }
    };


When you write '0' Qt interprets than a plausible intermediate value during editing. If you don't like this behavior, you need create an inheritance class from QIntValidator and re-implement the following function:

virtual QValidator::State validate ( QString & input, int & pos ) const

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消