【发布时间】:2016-12-17 06:30:02
【问题描述】:
在 QML 中(至少在版本 5.61 之前),一旦在 JavaScript 上下文中分配了新值,属性绑定就会被破坏:
Item {
property bool sourceBool: <some changing value e.g. from C++ code>
property bool boundBool: sourceBool
function reassignBool() {
boundBool = true;
}
}
一旦调用reassignBool,boundBool 将变为true,无论sourceBool 的状态如何。
我希望能够为不会破坏原始绑定的属性分配临时值;临时值将持续存在,直到与原始绑定关联的任何 NOTIFY 信号被触发,此时绑定属性将再次反映绑定计算的值。
作为一个示例用例,假设我有一个按钮,我不希望用户能够连续按两次,并且根据某些规则启用或禁用该按钮:
MyButton {
id: onceOnlyButton
// Suppose the QML type `MyButton` provides a boolean property
// called `enabled` that greys out the button and prevents it from
// being clicked when `false`.
enabled: <condition1> && <scondition2>
onClicked: {
<schedule some asynchronous work>
}
}
假设,当点击按钮时,<condition1> 将最终变为false,因此按钮最终将被适当地禁用——但不是立即。
所以我想做如下的事情:
....
onClicked: {
enabled = false
<schedule some asynchronous work>
enabled = Qt.binding(function() {
return <condition1> && <condition2>
}
}
...当然,一旦我重新建立绑定,因为condition1 还没有变成false,enabled 将再次变成true。
我想我可以创建某种Connections 对象,将与<condition1> 关联的NOTIFY 信号连接到调用Qt.binding 的处理程序,然后....删除@987654340 @对象,我想。但这似乎相当复杂和不雅。
有没有办法确保enabled 设置为false立即,然后尽快重新绑定到<condition1> 和<condition2> 的NOTIFY 信号发出了这些信号?
1 我不完全确定分配如何影响 5.7 中的绑定,但我知道 assigning a value to a property does not automatically break the binding。所以这可能会在 5.7 中自动开箱即用。
【问题讨论】:
标签: qt qml property-binding