Binding QML Type
允许任意创建属性绑定。更多
Import Statement: | import QtQml |
属性
- delayed : bool
- property : string
- restoreMode : enumeration
- target : QtObject
- value : var
- when : bool
详细说明
在 QML 中,属性绑定会导致不同对象的属性之间产生依赖关系。
绑定到不可访问的属性
有时需要把一个对象的属性绑定到另一个 QML 不能直接实例化的对象的属性上,如 C++ 导出到 QML 的类的属性。你可以使用绑定类型(Binding type)来建立这种依赖关系,把任何值绑定到任何对象的属性上。
例如,在映射 "app.enteredText" 属性到 QML 的 C++ 应用程序中,你可以使用 Binding 来更新 enteredText 属性。
TextEdit { id: myTextField; text: "Please type here..." } Binding { app.enteredText: myTextField.text }
当text
发生变化时,C++ 属性enteredText
将自动更新。
条件绑定
在某些情况下,你可能想在满足特定条件时修改属性值,但在其他情况下则不修改。通常情况下,直接绑定无法做到这一点,因为您必须为所有可能的分支提供值。
例如,下面的代码段会在您释放鼠标时发出警告。这是因为当鼠标未按下时,绑定的值是未定义的。
// produces warning: "Unable to assign [undefined] to double value" value: if (mouse.pressed) mouse.mouseX
绑定类型可以防止出现这种警告。
Binding on value { when: mouse.pressed value: mouse.mouseX }
绑定类型可恢复先前在属性上设置的任何直接绑定。
另请参阅 Qt Qml.
属性文档
delayed : bool |
此属性表示绑定是否应被延迟。
延迟绑定不会立即更新目标,而是要等到事件队列被清除。这可以作为一种优化手段,或防止分配中间值。
Binding { contactName.text.value: givenName + " " + familyName when: list.ListView.isCurrentItem delayed: true }
property : string |
restoreMode : enumeration |
该属性可用于描述禁用绑定时是否以及如何恢复原始值。
可能的值有
常量 | 说明 |
---|---|
Binding.RestoreNone | 完全不恢复原始值 |
Binding.RestoreBinding | 如果是另一种绑定,则恢复原始值。在这种情况下,旧的绑定再次生效。 |
Binding.RestoreValue | 如果是普通值而不是绑定值,则恢复原始值。 |
Binding.RestoreBindingOrValue | 始终恢复原始值。 |
默认值为Binding.RestoreBindingOrValue
。
注意: 该属性的存在是为了向后兼容 Qt 早期版本。请勿在新代码中使用。
target : QtObject |
value : var |
要在目标对象和属性上设置的值。它可以是一个常量(用处不大),也可以是一个绑定表达式。
只有在无法声明提供绑定目标时,才需要使用该属性。否则,可以直接绑定到目标。
when : bool |
该属性在绑定激活时保持不变。当你希望绑定处于活动状态时,应将其设置为求值为 true 的表达式。
Binding { contactName.text: name when: list.ListView.isCurrentItem }
默认情况下,当绑定变为非活动时,之前设置的任何绑定或值都会恢复。您可以使用restoreMode 属性自定义恢复行为。
另请参阅 restoreMode 。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.