Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Qt5 - Calling setContextProperty() with a QList<MyObject*>
Forum Updated to NodeBB v4.3 + New Features

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

Scheduled Pinned Locked Moved General and Desktop
1 Posts 1 Posters 1.4k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    koopajah
    wrote on last edited by
    #1

    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!

    1 Reply Last reply
    0

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved