Binding 使用场景
有时候,我们需要绑定一个不是QML直接实例化的组件的属性。一般是一个C++扩展的属性。或者这样的场景下,条件判断比如
value: if (mouse.pressed) mouse.mouseX
在这种情况下,一般的绑定不工作,而 Binding类型则允许我们绑定任何值到任何属性上。
一、Binding
属性 | 类型 | 解释 |
---|---|---|
property | string | 被更新的属性 |
target | Object | 被更新的目标 |
delayed | bool | 延迟绑定不会立即更新目标,而是等到事件队列已被清除。这可以作为一个优化,或防止中介值被分配 |
value | any | 要在目标对象和属性上设置的值,它能是一个常数(不常用),或者绑定的表达式 |
when | bool | 绑定是否被激活,它应该被设置成表达式,用以判断我们是否想激活绑定 |
restoreMode | enumeration | 当绑定条件不符合时,描述当且时应该如何恢复原始值 |
restoreMode:
Binding.RestoreNone The original value is not restored at all
Binding.RestoreBinding The original value is restored if it was another binding. In that case the old binding is in effect again.
Binding.RestoreValue The original value is restored if it was a plain value rather than a binding.
Binding.RestoreBindingOrValue The original value is always restored.
二、使用步骤
1.绑定到无法访问的属性:
有时候,我们需要绑定一个不是QML直接实例化的组件的属性。一般是一个C++扩展的属性。在这种情况下,一般的绑定不工作,Binding允许我们绑定任何值到任何属性上。
例如,一个C++应用程序影射了一个叫app.enteredText的属性到QML,我们可以用Binding属性来更新app.enteredText,就像下面的例子这样:
TextEdit {
id: myTextField;
text: "Please typehere..."
}
Binding {
target: app;
property: "enteredText";
value: myTextField.text
}
当TextEdit被更新,则C++属性也将更新。
2.绑定Item property:
Item
{
id: item
property rect rectangle: Qt.rect(0, 0, 200, 200)
}
Binding {
target: item
property: "rectangle.x"
value: 100
}
Binding {
target:contactName;
property: 'text'
value: name;
when: list.ListView.isCurrentItem
}
3.根据条件绑定到单分支。
有时候,我们希望当某些条件为真时,属性的值能被控制。而所有其他情况下,我们放弃对属性的控制。这时候,直接完成绑定是不可能的,因为这需要为所有可能的分支提供值。
例如:
// produces warning: "Unable to assign [undefined]to double value"
value: if (mouse.pressed) mouse.mouseX
在上面的例子中,无论什么时候释放鼠标,警告都会发生。因为当鼠标没有被按下时,value没有定义。注意,上面的属性加冒号,就是通常的绑定方法。
与之区别的,是我们使用Binding来处理这种预期,以避免警告。例如下面的代码:
Binding on value {
when:mouse.pressed
value:mouse.mouseX
}
Binding组件也能恢复预先直接绑定在属性上的值,从这个角度来说,这个组件就像是一个简化版的State。
下面的代码等效于上面的Binding:
State {
name:"pressed"
when:mouse.pressed
PropertyChanges {
target: obj
value: mouse.mouseX
}
}
如果绑定的目标或属性更改,绑定值会立刻被推送到新目标上