Search code examples
regexqtqmlqtquick2qtquickcontrols

How to apply regexp to TextEdit like in Qt Widgets?


Is there a way to apply regexp (while input some text) to TextEdit QML element like in QtWidgets?

In QtWidgets you need to create QRegExp and QValidator, then set pattern for QRegExp, create a QValidator with the pattern and finally call setValidator() on QLineEdit.

Is there a way to implement something similar in QML? Or the only way is to workaround is by exploiting some JavaScript and/or C++ code?


Solution

  • If you want to add text validation you should switch from TextEdit to TextInput type. The latter has a validator property. It reads from the documentation:

    Allows you to set a validator on the TextInput. When a validator is set the TextInput will only accept input which leaves the text property in an acceptable or intermediate state. The accepted signal will only be sent if the text is in an acceptable state when enter is pressed.

    Currently supported validators are IntValidator, DoubleValidator and RegExpValidator.

    RegExpValidator provides the regExp property which holds the actual regular expression to be applied to the input text.

    Here is a minimum example which accepts only digits and a (one or more digit/a - both uppercase and lowercase):

    import QtQuick 2.4
    import QtQuick.Window 2.2
    import QtQuick.Controls 1.3
    
    ApplicationWindow {
        id: window
        width: 200
        height: 200
        visible: true
        
        TextInput {
            focus: true
            anchors.centerIn: parent
            validator: RegExpValidator { regExp: /[0-9aA]+/ }
        }
    }