【问题标题】:Using InputMask in QML在 QML 中使用 InputMask
【发布时间】:2013-12-10 19:38:45
【问题描述】:

我有一个小的显示窗口,它应该包含一个像“0000.00”这样的 InputMask。单击 0 到 9 的数字按钮时,显示屏应显示相应的数字,例如:0345.89 这是我的代码:

TextInput {
    id: displayNumbers6Text
    cursorVisible: true
    focus: true
    validator: RegExpValidator {
        regExp: /[0-9]+/
    }
    inputMask: "0000.00"
    maximumLength: 7
}

对于按钮:

Button {
     width: parent.width*0.3
     height: parent.height*0.15
     buttonColor: "#000000"
     MouseArea {
          anchors.fill: parent
          onClicked: {
                displayNumbers6Text.text = "1"
          }
     }
}

但它不起作用。我做错了什么?

【问题讨论】:

    标签: qml


    【解决方案1】:

    当您分配text 属性时,您将此值重置为“1”。 如果您尝试的是在单击按钮时插入一个值,您可以试试这个:

    import QtQuick 2.0
    
    Rectangle {
        width: 360
        height: 200 
    
        TextInput {
            id: displayNumbers6Text
            width: parent.width
            height: parent.height * 0.5
    
            cursorVisible: true
            focus: true
            validator: DoubleValidator {
            }
            inputMask: "0000.00"
            maximumLength: 7
    
            function appendNum(num) {
                var dotPos = text.indexOf(".");
                if (dotPos == 4)
                    text += num;
                else
                    text = text.substr(0, dotPos) + num + text.substr(dotPos);
            }
        }
    
        Rectangle {
            width: parent.width*0.3
            height: parent.height*0.15
            anchors.top: displayNumbers6Text.bottom
            color: "black"
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    console.log(displayNumbers6Text.text);
                    displayNumbers6Text.appendNum("1");
                }
            }
        }
    }
    
    • 您可以使用 DoubleValidator 代替一般的 RegexValidator,它会更具可读性。
    • 我将 appendNum 函数添加到 TextInput 以在文本字符串的末尾插入一个值。请注意,点字符始终在字符串中,因为您设置了inputMask

    【讨论】:

    • 谢谢!这就是我一直在寻找的。我只有一个错误:单击数字时,它们的位置不是从左到右或从右到左的顺序,而是看似不合理:首先在点的左侧,然后在单击第二个按钮后,第一个数字向右移动,为第二个数字腾出空间,依此类推。我怎样才能让他们都呆在同一个地方?
    • @user3069706 很好,我修正了关于子字符串定界的小错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多