New qml object added to scene in c++

662 views Asked by At

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?

2

There are 2 answers

0
cmannett85 On

You need to specify a parent for the item otherwise it isn't a part of the visual hierarchy and won't be rendered.

0
lolo On

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.