请参考从C++加载QML对象:
QQuickView view;
view.setSource(QUrl("qrc:/main.qml"));
view.show();
QQuickItem *root = view.rootObject()
QQmlComponent component(view.engine(), QUrl("qrc:/Button.qml"));
QQuickItem *object = qobject_cast<QQuickItem*>(component.create());
现在您已经创建了一个自定义组件的实例。
为避免Javascript垃圾收集器将其删除,请告诉QML由C++负责:
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership)
你需要2个父级:一个可视父级来显示对象和一个QObject父级,
以确保在删除view
时正确地删除object
。
object->setParentItem(root);
object->setParent(&view);
可以像在QML中一样自由地设置object
的任何属性。为了确保QML知道这些更改,请使用以下函数:
随意设置object
的任何属性,就像在QML中一样。要确保QML知道这些更改,请使用以下函数:
object->setProperty("color", QVariant(QColor(255, 255, 255)));
object->setProperty("text", QVariant(QString("foo")));
已完成。
替代的QQmlEngine版本:
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQuickWindow *window = qobject_cast<QQuickWindow*>(engine.rootObjects().at(0));
if (!window) {
qFatal("Error: Your root item has to be a window.");
return -1;
}
window->show();
QQuickItem *root = window->contentItem();
QQmlComponent component(&engine, QUrl("qrc:/Button.qml"));
QQuickItem *object = qobject_cast<QQuickItem*>(component.create());
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
object->setParentItem(root);
object->setParent(&engine);
object->setProperty("color", QVariant(QColor(255, 255, 255)));
object->setProperty("text", QVariant(QString("foo")));