在QML中使用InputMask

在QML中使用InputMask,qml,Qml,我有一个小的显示窗口,应该可以容纳输入掩码,如“0000.00”。单击0到9之间的数字按钮时,显示屏应显示相应的数字,例如:0345.89 这是我的密码: TextInput { id: displayNumbers6Text cursorVisible: true focus: true validator: RegExpValidator { regExp: /[0-9]+/ } inputMask: "0000.00"

我有一个小的显示窗口,应该可以容纳输入掩码,如“0000.00”。单击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"
          }
     }
}

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

当您指定
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,它将更具可读性
  • 我在
    TextInput
    中添加了一个appendNum函数,以便在文本字符串的末尾插入一个值。请注意,由于设置了
    inputMask
    ,因此点字符始终位于字符串中

谢谢!这就是我要找的。我只有一个错误:单击数字时,它们的位置不是从左到右或从右到左的顺序,而是似乎不合理的:首先在点的左侧,然后在单击第二个按钮后,第一个数字向右移动,为第二个数字留出空间,依此类推。我怎么能让它们都呆在同一个地方?@user3069706 Well-spot,我修正了关于子串定界的小错误