我想创建一个自定义组件,它允许通过以下(传统)设置进行双向绑定:
// main.qml
property var someStoredValue: someInitialValue // may be C++ property in real application
MyCustomComponent
{
myProperty: someStoredValue // this binding will be destroyed on user input
onMyPropertyChanged: someStoredValue = myProperty
}
// MyCustomComponent.qml
Item
{
property var myProperty: null
MouseArea
{
anchors.fill: parent
onClicked: myProperty = "some text or other value" // breaks the binding set in main.cpp
}
}
MyCustomComponent
应该能够更新 myProperty
(以编程方式),而不破坏 someStoredValue
和 myProperty
之间的绑定。我如何改变MyCustomComponent
的实施来实现我的目标?
一种解决方案是使用
Binding
对象来更新 myProperty
内的 MyCustomComponent
,而不是直接更改值:
// MyCustomComponent.qml
Item
{
property var myProperty: null
Binding on myProperty
{
id: myPropertyUpdater
function set(newValue) {value = newValue; when = true; when = false;}
when: false
}
MouseArea
{
anchors.fill: parent
onClicked: myPropertyUpdater.set("some text or other value")
}
}
诀窍是立即将
when
的 Binding
属性设置为 true,以传播新值。停用 Binding
(when = false;
) 后,任何先前的直接绑定都将恢复,如 docs 中所述:
当绑定再次变为非活动状态时,之前的任何直接绑定 之前在该属性上设置的内容将被恢复。
缺点是,如果更改的值未存储在
onMyPropertyChanged
处理程序中,myProperty
将恢复为旧值。