我面临一个大问题,需要花费大量时间才能修复,因为我不知道原因以及如何修复它。问题真的很简单:我有一个示例 QML 组件定义为:
Rectangle {
id: rect
property bool test: myclass.testproperty
Rectangle {
width: 50
height: 50
visible: parent.test
}
}
我连接了一个 MouseArea onClicked 信号来做到这一点:
test = !test
所以我切换 bool 变量的值。为了使用 READ、WRITE 和 NOTIFY 信号将值从 C++ 推送到 QML 以及从 QML 推送到 C++ Q_PROPERTY,我使用了这个
Binding {
target: myclass
property: "testproperty"
value: rect.test
}
一切正常,直到我单击 mouseArea 并通过绑定(bind)推送更改。之后,每次我尝试从 C++ 设置新的属性值时,我都看不到 QML 中的任何变化,就像绑定(bind)被破坏一样。但是,如果我尝试单击 MouseArea,我仍然会调用 C++ 类的 setTestProperty 方法。基本上,它不同步 C++ -> QML 方式。为什么?我找不到问题,发出信号是因为 QSignalSpy 给了我 1 作为使用后的发射次数
emit this->testPropertyChanged(newvalue)
编辑
这里有一个例子:基本上在这里我们使用具有相同信号的 QString 属性。唯一改变的是,我没有使用 Rectangle QML 元素并绑定(bind)到自己的属性,而是使用 TextInput 元素
TextInput {
id: mytext
text: myclass.testproperty
}
Binding {
target: myclass
property: "testproperty"
value: mytext.text
}
最佳答案
这里没有问题。这是标准的 QML 绑定(bind)行为。当您在 JavaScript 代码中更改某些 QML Widget 的属性时,所有对其的声明性绑定(bind)都将终止。您可以选择在事件处理程序的 JS 代码中使用声明性绑定(bind)或手动更新值。
编辑
Rectangle {
id: rect
// Establishing initial value for 'test' property via QML binding
property bool test: myclass.testproperty
// Manual update of 'test' property when binding will be broken
Connections {
target: myclass
onTestpropertyChanged: {
rect.test = xxx
}
}
}
关于c++ - QML 双向 C++ 绑定(bind)不再接收更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11908890/