在不破坏绑定的情况下更改属性值以支持双向绑定

问题描述 投票:0回答:1

我想创建一个自定义组件,它允许通过以下(传统)设置进行双向绑定:

// 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
的实施来实现我的目标?

qt data-binding qml 2-way-object-databinding
1个回答
2
投票

一种解决方案是使用

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
将恢复为旧值。

© www.soinside.com 2019 - 2024. All rights reserved.