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").

    MyModel.h:

    @class MyObject: public QObject
    {
    Q_OBJECT

    Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)

    public:
    MyObject(QObject *parent=0);
    ~MyObject();

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

    Q_SIGNALS:
    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();
    ctxt->setContextProperty("myModel",QVariant::fromValue(listElems));
    @

    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?

    Thanks!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.