文本字段的动态验证器

问题描述 投票:0回答:1

在桌面应用程序中,我有一个简单的文本字段(QtQuick.Control 2),它根据状态用不同的颜色装饰。它还应该根据当前状态使用不同的 RegExpValidator(带有另一个正则表达式)。

如何在运行时切换/更改/修改 RegExpValidator? (例如,当按下 PushButton 或触发 onEditingFinished-Event 时)

当前 QML 代码:


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"
}

最终目标是用于输入键值对的输入线(我可以在其中对特定键使用特定的 RegExpValidator。)

这里应该使用RegExpValidator来输入密钥,例如“author:”+按Enter键(键盘输入模式)

EnterKey

切换到valueinput-mode后,应该使用另一个RegExpValidator:

KeyEntered

qt qml
1个回答
6
投票
property var valid1 : IntValidator { bottom:0; top: 2000}
property var valid2 : IntValidator { bottom:2000; top: 4000}

...
validator: if(condition) { valid1 }
else { valid2 }
© www.soinside.com 2019 - 2024. All rights reserved.