Important: Please read the Qt Code of Conduct -

Qt5 - Calling setContextProperty() with a QList<MyObject*>

  • Hey everyone!

    I based my code on the examples found in the documentation of Qt Quick 2.0 to provide data to a ListModel in my QML dynamically from C++ (Found in "examples/quick/models/objectlistmodel").


    @class MyObject: public QObject

    Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)

    MyObject(QObject *parent=0);

    QString name() const;
    void setName(const QString &name);
    QString deviceName;

    void nameChanged();

    QML file:

    import QtQuick 2.0

    ListView {
    width: 100; height: 100

    model: myModel
    delegate: Rectangle {
        height: 25
        width: 100
        Text { text: name }


    In my Main.cpp I now create a QList<QObject *> that I fill with some instances of MyModel and it works:

    QList<QObject *> listElems;
    listElems.append(new MyModel());
    listElems.append(new MyModel());

    QQmlContext *ctxt = view->rootContext();

    But if instead of using a QList<QObject *> I use a QList<MyModel *> then I get errors when loading the QML indicating that the property name is not defined:

    bq. qrc:view.qml:10: ReferenceError: name is not defined

    I tried using qRegisterMetaType<T>() and qmlRegisterType<T>() without success. What am I doing wrong?


Log in to reply