Hector Lorenzo
Hector Lorenzo

Reputation: 169

Expose List of QAbstractModelList to QML

Im writting a QML/Qt application. I implemented a model in c++. The class for this model is derived from QAbstractListModel. Now i need to put the objects of this class into a list and expose it to QML so that it can be used in QML like this:

DraggableItemList{
            listModel: listofmodels[0]
}

I tried to simply put the objects into QList and expose the QList like this:

engine.rootContext()->setContextProperty("listofmodels",QVariant::fromValue(modelList));

Unfortunately, this led to an error because QAbstractListModel is not copy-able. So i tried it with a QList of pointers of each model:

QList<myModel *> modelList;

But within qml it did not display the model by using model pointers. Is there any other solution to solve this problem?

Upvotes: 1

Views: 518

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

You have to use QVariantList, for example, using the model in this example, we would use the following:

*.cpp

#include "model.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    QVariantList modelist;

    for(int i=0; i< 10; i++){
        AnimalModel *model = new AnimalModel;
        model->addAnimal(Animal("Wolf", "Medium"));
        model->addAnimal(Animal("Polar bear", "Large"));
        model->addAnimal(Animal("Quoll", "Small"));
        modelist << QVariant::fromValue(model);
    }

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("modelist", modelist);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

*.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListView {
        width: 200; height: 250
        model: modelist[0]
        delegate: Text { text: "Animal: " + type + ", " + size }
    }
}

You can find the complete example in the following link

Upvotes: 4

Related Questions