c++qtqmlqt5qt5.9

How to access a qml ListElement from c++


I have a ListModel:

ListModel {
  ListElement {
    property: "value"
  }
  ListElement {
    property: "value2"
  }
}

which I am trying to access from a c++ Qt class.

I've managed to get a reference to the listmodel:

QQmlEngine engine;
QQmlComponent component(&engine,
            QUrl("qrc:///path.qml"));
QObject *object = component.create();

Debbuging the object gives me a QQmlListModel(adress).
object -> chlidren() gives me nothing, object -> children().count() shows 0.
I tried making a QList or QTableView from the object, but with no luck.

How can I get the values of the ListElements ?


Solution

  • As QQmlListModel inherits QAbstractItemModel you can use all methods provided and implemented by this class.

    More specifically you will be looking for:

    Then you can easily iterate over the model.

    QQmlComponent component(&engine, "MyQmlListModel.qml");
    QObject* o = component.create();
    QAbstractListModel* m = qobject_cast<QAbstractListModel*>(o);
    
    if (m != nullptr) {
        qDebug() << m->rowCount();
        qDebug() << m->data(m->index(0, 0), 0);
    }
    else { qDebug() << "failed!"; }