我需要在运行时从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);
Run Code Online (Sandbox Code Playgroud)