Home Ask Login Register

Developers Planet

Your answer is one click away!

user3821746 February 2016

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.

Answers


ddriver February 2016

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.

Post Status

Asked in February 2016
Viewed 3,322 times
Voted 5
Answered 1 times

Search




Leave an answer


Quote of the day: live life