Search code examples
qtqml

Dynamic validator for TextField


In a desktop application, I have a simple TextField (QtQuick.Control 2) which is decorated with different colors depending on a state. It should also use a different RegExpValidator (with another regular expression) depending on the current state.

How I can switch/change/modify a RegExpValidator at runtime? (e.g., when a PushButton is pressed or onEditingFinished-Event is triggered)

Current QML code:


import QtQuick 2.3
import QtQuick.Controls 2.2 as Quick
import QtQuick.Layouts 1.3

RowLayout {
    id: layout
    property color modeColor: "whitesmoke"
    property color modeTextColor: "gray"

    spacing: 0
    Rectangle {
        id: rect
        Layout.fillWidth: true 
        Layout.minimumWidth: 100 
        Layout.preferredWidth: 100
        Layout.maximumWidth: 100
        Layout.preferredHeight: layout.implicitHeight
        color: modeColor
        border.width: 1
        border.color: modeColor
        Text {
            id: recttext
            anchors.centerIn: parent
            text: "Enter key"
            color: modeTextColor
        }
    }

    Quick.TextField {
        id: input
        Layout.fillWidth: true
        placeholderText: "Text"
        background: Rectangle {
            color: "whitesmoke"
            border.width: 1
            border.color: modeColor
        }
        validator: RegExpValidator { regExp: /.*:$/ } 
        onEditingFinished: {
            recttext.text = input.text

            if (layout.state == "keyinput") {
                layout.state = "valinput"
                // should change to another regExp validator
            } else {
                layout.state = "keyinput"
                // should change to another regExp validator
            }
            input.clear()
        }
        Keys.onPressed: {
            if (event.key == Qt.Key_Escape) {
                    layout.state = "keyinput"
                    recttext.text = "Enter key"
                    input.clear()
            }
        }
    }

    states: [
        State {
            name: "keyinput"
            PropertyChanges { target: layout; modeColor: "whitesmoke"; modeTextColor: "gray" }
        },
        State {
            name: "valinput"
            PropertyChanges { target: layout; modeColor: "red"; modeTextColor: "white" }
        }
    ]
    state: "keyinput"
}

The end goal is an inputline for entering key-value pairs (where I could use a specific RegExpValidator for a specific key.)

Here it should use RegExpValidator for entering a key, e.g., "author:" + Pressing Enter (keyinput-mode)

EnterKey

After switching into the valueinput-mode, it should use another RegExpValidator:

KeyEntered


Solution

  • property var valid1 : IntValidator { bottom:0; top: 2000}
    property var valid2 : IntValidator { bottom:2000; top: 4000}
    
    ...
    validator: if(condition) { valid1 }
    else { valid2 }