简体   繁体   中英

Its possible write an context property on QML from C++?

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?

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;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM