Important: Please read the Qt Code of Conduct -

Why manually map C++ object properties and QML elements?

  • Hi,

    I was wondering, let's say you define your own QML "element" :


    Rectangle {
    property string text: ""
    color: "black"

    Text {
        id: dialogText
        anchors.centerIn: parent
        text: parent.text
        color: parent.color


    Now I want to map my C++ Object (text and color properties) to this own defined Dialog qml element. How to do this?

    C++ Object:

    class Dialog : public QObject
    Q_PROPERTY(QString text READ Text NOTIFY TextChanged)
    Q_PROPERTY(QString color READ Color NOTIFY ColorChanged)

    Dialog(QObject *parent = 0);

    const QString & Text();
    const QString & Color();   

    void TextChanged();
    void ColorChanged();

    QString mText;
    QString mColor;

    If I do a setContextProperty() I still have to manually set all the properties of the Dialog.qml to the C++ object:

    view.rootContext()->setContextProperty("myDialog", myDialogObject);

    And Qml:

    Dialog { text: myDialog.text; color: myDialog.color }

    Is there a way that QML automatically maps the properties of the C++ object to the QML element?

    I have seen that if I make C++ Dialog object a plugin (QDeclarativeItem) I still need to manually map the properties!

    Enlighten me please :)

Log in to reply