[英]Its possible write an context property on QML from C++?
I need to create the context property "model(QAbstractItemModel)" from C++. 我需要从C ++创建上下文属性“ model(QAbstractItemModel)”。
But, i just know the QQmlProperty::write(...), and this method just accepts QVariant as value for the property. 但是,我只知道QQmlProperty :: write(...),并且此方法只接受QVariant作为该属性的值。
Any suggestion? 有什么建议吗?
You must use QVariant::fromValue()
and pass it the model pointer, in the next part I show an example: 您必须使用QVariant::fromValue()
并将模型指针传递给它,在下一部分中,我将显示一个示例:
main.cpp 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 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;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.