0

I need to create the context property "model(QAbstractItemModel)" from C++.

But, i just know the QQmlProperty::write(...), and this method just accepts QVariant as value for the property.

Any suggestion?

Jhonny Pinheiro
  • 308
  • 3
  • 19

1 Answers1

1

You must use QVariant::fromValue() and pass it the model pointer, in the next part I show an example:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlProperty>
#include <QStandardItemModel>

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

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    QStandardItemModel model;
    for (int i=0; i<100; i++) {
        QStandardItem* item = new QStandardItem(QString("%1").arg(i,2,10,QChar('0')));
        model.appendRow(item);
    }
    QObject *obj = engine.rootObjects().first()->findChild<QObject *>("gv");
    QQmlProperty::write(obj, "model", QVariant::fromValue(&model));
    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

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

    GridView {
        anchors.fill: parent
        objectName: "gv"
        delegate: Rectangle {
            Text {
                text: display;
            }
        }
    }
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241