QGroundMap动态绘制MapPolyline异常:Instantiator使用问题求助
QGroundMap动态绘制多个MapPolyline的问题解决
我在重写QGroundMap时遇到了问题:需要在自定义QGround控件的QGroundMap上动态绘制多个MapPolyline对象,目前仅能通过直接注入的方式实现:
Component.onCompleted: { objMgr.createObjects([mapLine], _root.mapControl, true /* parentObjectIsMap */) }
标准的MapItemView及其他元素无法正常工作,尝试用Instantiator实例化多个MapPolyline也失败了:
Instantiator { id: testInstantiator model: globalCoordinates function getIndex(index) { console.log("currentIndexIs") console.log(index) return index } delegate: Component { id: mapLine MapPolyline { id: targetPolyLine line.width: 3 line.color: "red" z: QGroundControl.zOrderWaypointLines path: testInstantiator.model[index] } } }
我的坐标模型定义如下:
property var globalCoordinates: [ [QtPositioning.coordinate(42, 13), QtPositioning.coordinate(42, 18)], [QtPositioning.coordinate(42, 13), QtPositioning.coordinate(42, 20)], [QtPositioning.coordinate(42, 13), QtPositioning.coordinate(42, 22)], [QtPositioning.coordinate(42, 13), QtPositioning.coordinate(42, 24)], [QtPositioning.coordinate(42, 13), QtPositioning.coordinate(42, 26)] ]
只有把index替换成具体数字时,才能绘制出单条线:
Instantiator { id: testInstantiator model: globalCoordinates function getIndex(index) { console.log("currentIndexIs") console.log(index) return index } delegate: Component { id: mapLine MapPolyline { id: targetPolyLine line.width: 3 line.color: "red" z: QGroundControl.zOrderWaypointLines path: testInstantiator.model[1] // 仅能绘制单条线 } } }
解决方法
1. 修复Instantiator的数据源引用问题
在QML的Instantiator delegate上下文里,当模型是数组类型时,modelData会直接指向当前循环的数组项,不需要通过testInstantiator.model[index]获取。同时,delegate内的index是上下文自带的属性,不需要额外定义getIndex函数。修正后的代码:
Instantiator { id: testInstantiator model: globalCoordinates delegate: Component { MapPolyline { line.width: 3 line.color: "red" z: QGroundControl.zOrderWaypointLines path: modelData // 直接使用当前项数据 } } }
2. 确保MapPolyline正确挂载到MapControl
如果上述代码仍不生效,需要显式指定MapPolyline的父对象为QGroundMap的mapControl,确保它被正确添加到地图控件中:
Instantiator { id: testInstantiator model: globalCoordinates delegate: Component { MapPolyline { parent: _root.mapControl // 显式绑定到地图控件 line.width: 3 line.color: "red" z: QGroundControl.zOrderWaypointLines path: modelData } } }
3. 替代方案:使用Repeater
Repeater在QML中更适合用于重复创建可视元素,稳定性优于Instantiator,代码如下:
Repeater { model: globalCoordinates delegate: MapPolyline { parent: _root.mapControl line.width: 3 line.color: "red" z: QGroundControl.zOrderWaypointLines path: modelData } }
4. 验证模型数据有效性
可以在组件加载完成时打印坐标数据,确保所有QtPositioning.coordinate对象都正确初始化:
Component.onCompleted: { globalCoordinates.forEach((path, idx) => { console.log(`路径 ${idx} 坐标:`, path) }) }
内容的提问来源于stack exchange,提问作者Nazarii Muliak
相关产品推荐
相关产品推荐

