Reputation: 117
I have a problem with adding new QML object to existing scene.
My main.qml
source:
ApplicationWindow
{
id:background
visible: true
width: 640
height: 480
}
MyItem.qml
source:
Rectangle
{
width: 100
height: 62
color: "red"
anchors.centerIn: parent
}
Finally, here is my main.cpp
source:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQmlComponent *component = new QQmlComponent(&engine);
component->loadUrl(QUrl("qrc:/MyItem.qml"));
qDebug() << "component.status(): "<< component->status();
QObject *dynamicObject = component->create();
if (dynamicObject == NULL) {
qDebug()<<"error: "<<component->errorString();;
}
return app.exec();
}
main.qml
appears correctly but MyItem.qml
doesn't appear inside main.qml
. Component.status()
returns state Ready
, no errors on dynamicObject
. What am I doing wrong?
Upvotes: 0
Views: 709
Reputation: 714
I think you should use QQuickView
instead of QQmlEngine
. main.cpp
would be:
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
view.show();
QQmlComponent component(view.engine(), QUrl("qrc:/MyItem.qml"));
QQuickItem *item = qobject_cast<QQuickItem*>(component.create());
item->setParentItem(view.rootObject());
QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
return app.exec();
}
And you need to change main.qml
type from ApplicationWindow
to Item
Item
{
id:background
visible: true
width: 640
height: 480
}
It is easier, and this way you can create a class that extends QQuickView
and which manages the creation of your new items.
Upvotes: 0
Reputation: 22376
You need to specify a parent for the item otherwise it isn't a part of the visual hierarchy and won't be rendered.
Upvotes: 1