如何在运行时从C ++创建QQmlComponent?

时间:2014-11-02 21:27:42

标签: c++ qt object qml

我需要在运行时从C ++代码添加QML组件。我能够从' main.qml'创建ApplicationWindow。文件。窗口成功显示。问题是我无法将其他QML组件添加到此窗口。我在' button.qml'中指定了按钮。文件。所以我尝试创建另一个QQmlComponent并将ApplicationWindow设置为按钮的父级。 obj1-> children()的输出显示类型按钮的子项存在 (QQuickItem(0xcc08c0),Button_QMLTYPE_12(0xa7e6d0))。但是没有显示按钮。 当我尝试将Button staticaly添加到' main.qml'一切顺利。我在运行时创建QQmlComponent时遗漏了一些东西。

QQmlEngine engine;

QQmlComponent component1(&engine, QUrl("qrc:/main.qml"));
QQmlComponent component2(&engine, QUrl("qrc:/button.qml"));

QObject* obj1 = component1.create();
QObject* obj2 = component2.create();

obj2->setParent(obj1);

1 个答案:

答案 0 :(得分:19)

请参阅Loading QML Objects from C++

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());

现在您创建了自定义Button组件的实例。

为了避免Javascript垃圾收集器将其杀死,请告诉QML C ++负责处理它:

QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);

您需要2个父母:visual parent来显示对象和QObject父级, 确保在删除object时正确删除view

object->setParentItem(root);
object->setParent(&view);

随意在QML中将任何属性设置为object。为了确保,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")));