如何在C++中获取QML地图组件的中心坐标?
如何从QQuickWidget中获取Qt Location地图的中心坐标
问题场景
使用QQuickWidget加载QML地图代码后,地图显示正常,但获取地图中心坐标时遇到问题:
- 调用
findChild获取Map组件返回nullptr - 直接访问根对象的
center属性得到NaN
用到的QML代码
import QtQuick 2.0 import QtQuick.Window 2.14 import QtPositioning 5.15 import QtLocation 5 Item { width: Qt.platform.os == "android" ? Screen.width : 512 height: Qt.platform.os == "android" ? Screen.height : 512 visible: true property double center_latitude: 59.91 property double center_longitude: 10.75 Plugin { id: mapPlugin name: "osm" } Map { anchors.fill: parent plugin: mapPlugin center: QtPositioning.coordinate(center_latitude, center_longitude) zoomLevel: 14 copyrightsVisible: false } }
尝试过的C++代码
auto mp = m_quickWidget->rootObject()->findChild<QQuickItem*>("Map"); auto items = m_quickWidget->rootObject()->childItems(); auto center = mp->property("center").value<QGeoCoordinate>(); extent.setCenter(LLA{ center.latitude(), center.longitude(), 0.0 }); center = m_quickWidget->rootObject()->property("center").value<QGeoCoordinate>();
解决方案
1. 给QML中的Map组件添加objectName
findChild是通过组件的objectName属性查找对象的,原QML中的Map没有设置该属性,导致无法找到。修改Map部分代码:
Map { objectName: "map" // 添加此属性,用于C++端查找 anchors.fill: parent plugin: mapPlugin center: QtPositioning.coordinate(center_latitude, center_longitude) zoomLevel: 14 copyrightsVisible: false }
2. 正确获取Map对象并读取实时中心坐标
修改C++代码,通过设置好的objectName找到Map组件,再读取其center属性:
QQuickItem* mapItem = m_quickWidget->rootObject()->findChild<QQuickItem*>("map"); if (mapItem) { QGeoCoordinate center = mapItem->property("center").value<QGeoCoordinate>(); if (center.isValid()) { extent.setCenter(LLA{ center.latitude(), center.longitude(), 0.0 }); } }
注意要判断对象是否存在、坐标是否有效,避免空指针或无效值问题。
3. 可选:通过根对象的自定义属性获取初始坐标
如果只需要初始设置的坐标,可以直接读取根Item的center_latitude和center_longitude属性,但这个值不会随地图拖动更新:
double lat = m_quickWidget->rootObject()->property("center_latitude").toDouble(); double lon = m_quickWidget->rootObject()->property("center_longitude").toDouble(); if (!qIsNaN(lat) && !qIsNaN(lon)) { extent.setCenter(LLA{ lat, lon, 0.0 }); }
内容的提问来源于stack exchange,提问作者Jepessen
相关产品推荐
相关产品推荐

