Dynamic property binding from c++



  • The following is a pure QML/C++ question (no graphics) - but this seemed to be closest forums category

    From C++ I want to dynamically (i.e. run time) create property bindings in a QObject or QQmlContext (or whatever works).
    I can do the following and it of course works as expected
    @container->setProperty("x", 1)
    container->setProperty("y", 2)
    int x = container->property("x)
    @

    but what i am looking for is the equivalent of
    @container->setProperty("sumXY", "int", "{ return x+y}"));@

    to be called from c++ (where the third argument would be string of javascript). it would be the equivalent of the qml definition
    @property int sumXY : x+y
    @

    i can't find anything in the documentation that indicates how to do this but it seems that it should be possible as it is what the qml "compiler" is doing. another way of stating the issue: is there a c++ equivalent to the Qt._binding() function defined in qml (which takes a javascript definition for the binding)?

    I am new to qml so am probably missing something obvious.



  • Check out "Binding QML Type":http://qt-project.org/doc/qt-5/qml-qtqml-binding.html

    What I understand from your query is that you want to add two dynamic properties X & Y and a third property whose value will always be sum of X and Y.

    I didn't try it but this is what I suggest. Add the third property Z and dynamically create a qml component. This component should have this Binding element which will bind the value of X & Y to Z.
    You Binding element shall look like this
    MyBinding.qml
    @Binding { target: myItem; property: "z"; value: "myItem.x + myItem.y" }@


  • Moderators

    Hi,

    In case of your example you can connect signal (i.e xChanged()) to slot and then there use setProperty viz. when x value changes the slot gets called. It is similar to binding. But in case of "x+y" it would be tricky as you would have to call slot when "x+y" changes.



  • thanks for the responses.

    i think the Binding component approach is a good idea - the trick will be to do it so that individual properties can be defined and assigned bindings as needed. i will be looking into this


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.