Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Cascading properties



  • To improve readability of my code I want to bind the value of a property to another.
    For example, in QML I define:

    property real _voltage
    
    Component.onCompleted() {
        _voltage = MyApp.data["123"]
    }
    

    MyApp class handles data as follow:

    public:
        Q_PROPERTY(QVariantMap data READ data NOTIFY dataChanged)
        QVariantMap data() const { return _mapData; }
    
    private:
        QVariantMap _mapData;
    
    signals:
        void dataChanged();
    

    whenever I change the value of an item of _mapData I emit the dataChanged() signal.
    In QML if I bind something to the MyApp.data() function it works fine (i.e. the text property is updated correctly) but if I use _voltage it doesn't update.

    I mean: MyApp.data["123"] updates according to the actual value in MyApp while voltage keep the value it had when I assigned it (_voltage = MyApp.data["123"]).

    Instead I expect it should update too because it's bound to MyApp.data["123"]. Is there a way to do what I want?


  • Moderators

    @Mark81 said in Cascading properties:

    _voltage = MyApp.data["123"]

    That's an assignment (imperative), not a binding.

    This is a declarative assignment (binding):

    property real _voltage: MyApp.data
    

    If you need a more advanced binding, use Binding component.



  • @sierdzio Oh thank you. I admit I didn't get the difference! I thought it was the very same thing, just at different time.


  • Moderators

    @Mark81 said in Cascading properties:

    @sierdzio Oh thank you. I admit I didn't get the difference! I thought it was the very same thing, just at different time.

    Here is how to remember it easily:

    • a = b assigns value of b to a at that exact moment when it is called (imperative assignment, same as in C++ or JS)
    • a: b updates a when b changes (declarative assignment)

Log in to reply