qtqmlqt5qvalidator

How do i get a QT validator to work correctly when pasting text?


I have a QT QRegExpValidator (RegExpValidator in QML) which restricts my text input to alphanumeric content only.

However, when users paste strings into my TextField sometimes these strings end in a newline character, which fails validation, and so the string never gets pasted.

I have read that implementing the fixup method gives you a chance to clean up the strings so they work properly with the validator. However, this does not appear to work when pasting - the strings still do not get pasted.

How do i get this to work the way i want?

My code looks as follows:

LoginValidator { id: alphaNumValidator; regExp: /(?:[0-9A-Za-z])+$/ }

And the LoginValidator implementation is as follows:

class LoginValidator : public QRegExpValidator
{
    Q_OBJECT
public:

    virtual void fixup(QString &input) const override
    {
        input = input.simplified().remove(' ');
    }
};

Solution

  • It seems that the fixup method doesn't get called in the validate method of a QRegExpValidator. To get this working, I had to reimplement the validate method and call the fixup method there before calling the parent validate method.

    QValidator::State LoginValidator::validate(QString &input, int &pos) const
    {
      fixup(input);
      return QRegExpValidator::validate(input, pos);
    }