Search code examples
c++qtqmlqt5qqmlcontext

expose a C++ object to QML and listen to change events


I have an object that I define in C++ and am trying expose a member string to QML. The class is defined as:

#ifndef MYTYPE_H
#define MYTYPE_H
#include <QString>
#include <QObject>


class MyType : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString foo READ foo WRITE setFoo NOTIFY fooChanged)

public:
    MyType(QObject *parent = nullptr) :
        QObject(parent),
        mFoo("0")
    {
    }

    QString foo() const
    {
        return mFoo;
    }

    void setFoo(QString foo)
    {
        if (foo == mFoo)
            return;

        mFoo = foo;
        emit fooChanged(mFoo);
    }

signals:
    void fooChanged(QString foo);

private:
    QString mFoo;
};

#endif // MYTYPE_H

So I am trying to expose the mFoo object to QML. Now, I am setting it with the application context as:

QtQuickControlsApplication app(argc, argv);
QQmlApplicationEngine engine(QUrl("qrc:/main.qml"));

qmlRegisterType<MyType>("MyType", 1, 0, "MyType");
MyType myType;
QObject *topLevel = engine.rootObjects().value(0);

engine.rootContext()->setContextProperty("foo", &myType);

Now in my qml, how can I listen to the change of the string that I am exposing. So I would like a listener method that gets called every time the mFoo member is changing.


Solution

  • You can use the Connections-object for that.

    Connections {
        target: yourContextProperty
        onFooChanged: console.log('I do something cool when foo changes!')
    }
    

    See also here some more examples, how to use context properties. (It also has an example for Connections)