user3069706
user3069706

Reputation: 21

Using InputMask in QML

I have a small display window, that should hold an InputMask like "0000.00". When clicking on the Number-Buttons from 0 to 9, the display should show the respective numbers, for example: 0345.89 Here is my code:

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

And for the Buttons:

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

But it doesn't function. What am I doing wrong?

Upvotes: 2

Views: 9852

Answers (1)

epsilon
epsilon

Reputation: 2969

When you assign text property, you reset this value to "1". If what you are trying is to insert a value when clicking on a button, you can try this :

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");
            }
        }
    }
}
  • You can use DoubleValidator instead of a general RegexValidator, it will be more readable.
  • I add an appendNum function to TextInput to insert a value at the end of the text string. Note that the dot character is always in the string, beacause of the inputMask you set

Upvotes: 2

Related Questions