我有以下
TextInput
元素:
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"
}
}
]
}
我想在通过退格键删除所有内容后显示
00
。我为此目的编写了一个State
,但它没有按预期工作。我做错了什么?
您在上面的代码中出现:“QML TextInput:检测到属性“text”的绑定循环”错误。原因是,当您将文本设置为“00”时,长度发生变化,这会再次触发“when”子句(并再次设置),并导致循环错误。
这是使用验证器的解决方法:
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
}
或者也许将文本绑定到函数:
text: myFunction()
与 onTextChanged 事件结合使用,可以产生更好的结果:
onTextChanged: {
//some code
myFunction()
}
function myFunction(){
//some validation
return "00"
}
对于 TextField 有这样的属性 placeholderText - 像这样使用它:
TextField {
id: textInput
text: m_init
placeholderText: "00"
...
}
将信号长度绑定到处理程序。更改以下代码:
onLengthChanged: {
if (length === 0) {
text = "00"
selectAll()
}
else undefined
}
此处需要 selectAll()
,以便能够从 "00"
清除输入字段