简体   繁体   中英

Instantiating QML object in existing C++ QT Project

We have an existing QT project written in C++, and we want to add something like the mapViewer example project to our existing UI. We can't figure out how to instantiate the mapViewer, and invoke the method that initializes/displays it. Following online help, we came up with the function below, that returns a QQuickWidget which we can add to a UI element. We keep getting an error that the created component never gets to be ready, so the function does not work.

QQuickWidget *buildMap(QWidget *parent)
{
    QQmlEngine *engine = new QQmlEngine;
    QQmlComponent component(engine, "qrc://mapviewer.qml");

    QObject *object = component.create();
    QMetaObject::invokeMethod(object, "initializeMap");

    QQuickWidget *map = new QQuickWidget(engine, parent);
    return map;
}

It does not make a ton of sense to us that we are creating an object using the mapViewer component, and then just forgetting about it, but the examples we found online have a flow similar to this.

Try something like this instead:

QQuickWidget *buildMap(QWidget *parent) {
    QQuickWidget *map = new QQuickWidget(parent);
    map->setSource(QUrl("qrc://mapviewer.qml"));
    map->show();
    return map;
}

As for the initializeMap method, maybe call it in mapviewer.qml 's onCompleted ? If you insist on calling it from C++, you can still get to the object thorugh map->rootObject()

Also, when creating components and objects, be that from C++ or QML, it is always a nice idea to check the status and output error strings if any, you don't just assume it will all work and then wonder why it doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM