Search code examples
qtqmlqt-signalsqproperty

Use signals or Q_PROPERTY to update QML objects


I'm very frequently receiving data from a server. This data is mainly composed of numbers. Each of them is corresponding to a QML object that would need to be updated.

What would be the best course of action between Q_PROPERTY and signals in order to update the QML objects from the C++ files?


Solution

  • Quite nice way is to use binding to C++ object from QML.

    F.ex. You have data class that should be shown to user as some qml object.

    You have C++ class with data and appropriate properties:

    class MyData
    {
        Q_OBJECT
        Q_PROPERTY(qreal number READ number NOTIFY numberChanged)
        ....
        //here you implement setter function that emits numberChanged() signal
    
    };
    

    You expose your data to qml via some helper classes or directly:

    view->rootContext()->setContextProperty("myData", myDataObject);
    

    Than you use binding to object in your qml:

    Text 
    {
        text: myData.number 
    }
    

    And now you can change the data in object of MyData class and your qml updates automatically.