1

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.

Quentin
  • 62,093
  • 7
  • 131
  • 191
Luca
  • 10,458
  • 24
  • 107
  • 234
  • 1
    Try to create a [`Connections`](http://doc.qt.io/qt-5/qml-qtqml-connections.html)-object with `target` to be your context property and handle there `onFooChanged`. I have not done it with context properties yet, and I can't test it right now. – derM - not here for BOT dreams Sep 01 '17 at 12:49
  • @derM Thanks! Did not know about this `Connections` object. It works! If you want to write it as an answer, please go ahead. – Luca Sep 01 '17 at 12:54
  • @Luca Not an answer but related. You don't have to call `qmlRegisterType` when you use your class only as a context property. – Macias Sep 02 '17 at 02:45

1 Answers1

1

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)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241