How to bind properties to an object's internal properties?
Solved
QML and Qt Quick
-
I want to bind rect.width to attr.width so that when I change attr.width, rect.width also changes. However, when I click the button, rect.width does not change. Only when attr is set to {"width": 110, "height": 50} can it be successful, but my attr is a large object and I don't want to change the entire attr.
Window { width: 740 height: 480 visible: true property var attr : {"width": 100, "height": 50} id: root Rectangle{ id: rect width: attr.width height: attr.height color: '#ff0000' } Button { x: 200 text: "Ok" onClicked: { //fail, rect.width not changed attr.width += 10 // success, rect.width changed // attr = {"width": 110, "height": 50} console.log('width', rect.width, attr.width) } } }
-
Hi @siman, and welcome!
Unfortunately, you cannot bind to the properties of a raw JavaScript object. You need to use a
QtObject
instead. When a QObject's property changes, it emits a signal to update other bindings. Raw JavaScript objects cannot emit signals.Replace
property var attr : {"width": 100, "height": 50}
with this:property QtObject attr: QtObject { property int width: 100 property int height: 50 }
-