Update QML map via C++
Unsolved
General and Desktop
-
Dear QT Community,
I have a QApplication with an embedded QQuickWidget (a map). I have managed to expose a pointer to the object that is needed to manipulate the current location. However, I cannot figure out how to update (refresh) the view with the newly set coordinates from C++.
May someone please help with this one...
Map::Map(QObject* qmlRootObject, QString specificObject) : QObject (Q_NULLPTR) { QObject* qmlSpecificObject = qmlRootObject->findChild<QObject*>(specificObject); this->openStreetMap = qmlSpecificObject; this->openStreetMapCenterObject = qvariant_cast<QObject*>(openStreetMap->property("center")); // Do something auto coordinates = this->openStreetMap->property("center").value<QGeoCoordinate>(); qDebug() << "Coordinates (original): " << coordinates; coordinates.setLatitude(coordinates.latitude() + 2); coordinates.setLatitude(coordinates.longitude() + 3); this->openStreetMap->setProperty("newLat", coordinates.latitude()); this->openStreetMap->setProperty("newLon", coordinates.longitude()); // the "center" attribute does not work as well qDebug() << "Coordinates (new): " << coordinates; }
Inside main.cpp
// Access the root object QQmlContext *context = engine.rootContext(); engine.load(QUrl(QStringLiteral("../TrackServ/map.qml"))); QObject *rootObject = engine.rootObjects().first(); Map* map = new Map(rootObject, "osmMap"); if (map == nullptr) { qDebug() << "ERROR: QML element not found..."; } else { qDebug() << "QML element found..."; context->setContextProperty("mapConnection", map); } return a.exec();
And the QML file:
import QtQuick 2.0 import QtQuick.Window 2.0 import QtLocation 5.6 import QtPositioning 5.6 Item { objectName: "mapItem" Plugin { id: osmPlugin objectName: "osmPlugin" name: "osm" PluginParameter { name: "osm.mapping.providersrepository.disabled" value: "true" } PluginParameter { name: "osm.mapping.providersrepository.address" value: "http://maps-redirect.qt.io/osm/5.6/" } } Map { objectName: "osmMap" anchors.fill: parent plugin: osmPlugin center: QtPositioning.coordinate(59.91, 10.75) // Oslo zoomLevel: 11 } }
-
Hi,
You should rather do it the other way around. Emit a signal from your C++ object and connect to it in your QML code and update there whatever you want.
-
Story continued here: https://forum.qt.io/topic/135852/binding-qquickwidget-to-qml-contex-inside-mainwindow