Editing C++ properties from QML with updates from C++
-
I currently try to implement a custom QML control that allows me to change values of C++ object properties but also is updated when the C++ object property changes on its own. I wonder if there really is no other way to do this.
So this is a working solution that I already have:
MyClass.h
Q_PROPERTY(int myCppValue READ myCppValue WRITE setMyCppValue NOTIFY myCppValueChanged)
MyCustomControl.qml
Item { property int value MouseArea { anchors.fill: parent onClicked: value = value + 1 } }
And now I instantiate this control as follows while assuming a MyClass instance is available as context property with the name "myclass":
MyCustomControl { id: my_control value: myclass.myCppValue /* from here things get messy */ Binding { target: myclass property: "myCppValue" value: my_control.value } Binding { target: my_control property: "value" value: myclass.myCppValue } }
My problem seems to be, that I cannot create an alias property in MyCustomControl that actually reads and modifies the value myclass.myCppValue. As soon as MyCustomControl assigns a new value to "value" I loose my connection to the myclass property. So the only way I could circumvent this problem is to create two bindings that connect these two values and just assign myclass.myCppValue as property value of my_control to get a nice initial value.
Is this the best you can do?
-
You could go the more imperative road, because now you have kind of endless update cycle:
Connections { target: myclass onMyCppValueChanged: if (my_control.value !== myclass.myCppValue) my_control.value = myclass.myCppValue } Connections { target: my_control onValueChanged: if (my_control.value !== myclass.myCppValue) myclass.myCppValue = my_control.value }
Then you would not have the cyclic update calles, that might lead to a problem.
-
@richardo I appreciate your input. Still I'm not sure I really like this approach that much better.
As for the cycle, I couldn't see any of those usual cyclic property warnings that QML gives you in those cases. I think this cycle is already properly broken by using the correct construction in setMyCppValue:
void setMyCppValue(int newValue) { if (newValue!=myCppValue) { myCppValue = newValue; emit myCppValueChanged(); } }