Qt4.7 QML TextInput empty state detection

2.1k views Asked by At

I have the following TextInput element:

TextInput {
    id: textInput
    text: m_init
    anchors.centerIn: parent
    font.family : "Helvetica"
    font.pixelSize: 14
    color: "black"
    maximumLength: 2
    smooth: true
    inputMask: "HH"

    states : [
        State {
            name: "EmptyInputLeft"
            when: !text.length

            PropertyChanges {
                target: textInput
                text : "00"
            }
        }
    ]
}

I would like to display 00 when everything has been removed from it by backspace. I've coded a State for this purpose but it does not work as expected. What am I doing wrong?

3

There are 3 answers

0
Felinor On

Bind the signal length to the handler. Change the following code:

onLengthChanged: {
            if (length === 0) {
                text = "00"
                selectAll()
            }
            else undefined
        }

selectAll() is required here in order to be able to clear the input field from "00"

0
Herald Smit On

You have a: "QML TextInput: Binding loop detected for property "text"" error on your code above. The reason is that when you are setting the text to "00", the length changes, which fires the "when" clause again (and setting again), and causes the loop error.

Here is a work-around using a validator:

TextInput {
    id: textInput
    text: m_init
    anchors.centerIn: parent
    font.family : "Helvetica"
    font.pixelSize: 14
    color: "black"
    maximumLength: 2
    smooth: true
    inputMask: "00"
    //validator: RegExpValidator { regExp: /^([0-9]|0[0-9]|1[0-9]|2[0-3])/ } //max 23 hours
    validator: RegExpValidator { 
         regExp: /^([0-9]|[0-9]/ } //any two digits

}

Or perhaps binding the text to a function:

text: myFunction() 

in conjunction with the onTextChanged event, could yield better results:

onTextChanged: {
 //some code
 myFunction()
}
function myFunction(){
//some validation
    return "00"  
}
0
dimril On

For TextField there is such property as placeholderText - use it like this:

TextField {
    id: textInput
    text: m_init
    placeholderText: "00"
    ...
}