【问题标题】:Qt4.7 QML TextInput empty state detectionQt4.7 QML TextInput空状态检测
【发布时间】:2015-05-27 14:02:49
【问题描述】:
我有以下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
qt-quick
qtdeclarative
【解决方案1】:
您在上面的代码中有一个:“QML TextInput: Binding loop detected for property "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"
}
【解决方案2】:
对于 TextField 有 placeholderText 这样的属性 - 像这样使用它:
TextField {
id: textInput
text: m_init
placeholderText: "00"
...
}