在PyQt中创建MapQuickItem并将其添加到Map中

问题描述 投票:3回答:1

我正在使用PyQt5通过UI文件中的QQuickWidget访问QML代码。我的QML文件创建了一个地图并绘制了点。我想从我的python代码中添加/修改这些点。我能够在python中访问QML中的Map对象,但是PyQt将它和MapQuickItem视为QQuickItems。我不确定如何在python中实际创建一个新的MapQuickItem并将其添加到Map对象。我尝试使用必要的属性创建一个QQuickItem,然后使用addMapItem方法,但收到此错误:

TypeError:无法将QQuickItem.addMapItem的参数0从'QQuickItem'转换为'QDeclarativeGeoMapItemBase *'“

我不知道如何在PyQt中创建一个QDeclarativeGeoMapItemBase对象,或者我是否应该以另一种方式进行此操作。

如您所见,我在正确引用QML文件中的对象时遇到了一些麻烦。 self.mapself.map.rootObject()在UI中获取了QQuickWidget,self.map.rootObject().children()[1]在QML中获取了Map对象。我更喜欢使用findChild()按ID查找项目,但是无法找到。有更好的方法吗?应该创建一个复制我的QML文件结构的Python对象吗?

这是QML代码的示例。我在UI文件中将此QML文件引用为QQuickWidget。

 Rectangle {
id:rectangle

Plugin {
    id: osmPlugin
    name: "osm"
}

property variant locationTC: QtPositioning.coordinate(44.951, -93.192)

Map {
    id: map
    anchors.fill: parent
    plugin: osmPlugin
    center: locationTC
    zoomLevel: 10

    MapQuickItem {
        coordinate: QtPositioning.coordinate(44.97104,-93.46055)
        anchorPoint.x: image.width * 0.5
        anchorPoint.y: image.height
        sourceItem:
            Image { id: image; source: "marker.png" }

    }
  }
}

下面是PyQt代码的示例,我尝试创建MapQuickItem并将其添加到地图中。

from PyQt5 import QtCore, uic, QtWidgets, QtPositioning, QtLocation, QtQml, QtQuick

form_class = uic.loadUiType("TTRMS.ui")[0]     

class MainWindow(QtWidgets.QMainWindow, form_class):
    '''
    classdocs
    '''
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)        

        tmc = QQuickItem()
        new_coordinate = QtPositioning.QGeoCoordinate()
        new_coordinate.setLatitude(44.951)
        new_coordinate.setLongitude(-93.192)
        tmc.setProperty("coordinate",new_coordinate)
        tmc.setProperty("anchorPoint",QtCore.QPointF(12.5, 32.0))
        image = QQuickItem()
        image.setProperty("source", QtCore.QUrl.fromLocalFile(("marker.png")))
        tmc.setProperty("sourceItem", image)
        image.setParent(tmc)
        self.map.rootObject().children()[1].addMapItem(tmc)

我在Windows 7上运行所有内容.PyQt5开发在Eclipse中使用PyDev和Python 3.4(32位),Qt Creator 5.5中的QML编码和Qt Designer 5.5中的UI完成。

python pyqt qml pyqt5
1个回答
0
投票

在你想用QML与C ++ / Python交互的情况下,最好将一些对象暴露给QML,它允许将C ++ / Python的数据传输到QML,因为后者具有不同的生命周期。

在这种特殊情况下,我将创建一个存储数据的模型,通过setContextProperty()将其发送到QML,并在QML端使用带有委托的MapItemView,这样您就可以拥有许多标记。

卖弄.朋友

import os
from PyQt5 import QtCore, QtWidgets, QtQuickWidgets, QtPositioning

class MarkerModel(QtCore.QAbstractListModel):
    PositionRole, SourceRole = range(QtCore.Qt.UserRole, QtCore.Qt.UserRole + 2)

    def __init__(self, parent=None):
        super(MarkerModel, self).__init__(parent)
        self._markers = []

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self._markers)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if 0 <= index.row() < self.rowCount():
            if role == MarkerModel.PositionRole:
                return self._markers[index.row()]["position"]
            elif role == MarkerModel.SourceRole:
                return self._markers[index.row()]["source"]
        return QtCore.QVariant()

    def roleNames(self):
        return {MarkerModel.PositionRole: b"position_marker", MarkerModel.SourceRole: b"source_marker"}

    def appendMarker(self, marker):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self._markers.append(marker)
        self.endInsertRows()

class MapWidget(QtQuickWidgets.QQuickWidget):
    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent,
            resizeMode=QtQuickWidgets.QQuickWidget.SizeRootObjectToView)
        model = MarkerModel(self)
        self.rootContext().setContextProperty("markermodel", model)
        qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
        self.setSource(QtCore.QUrl.fromLocalFile(qml_path))

        positions = [(44.97104,-93.46055), (44.96104,-93.16055)]
        urls = ["http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_gray.png", 
                "http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_red.png"]

        for c, u in zip(positions, urls):
            coord = QtPositioning.QGeoCoordinate(*c)
            source = QtCore.QUrl(u)
            model.appendMarker({"position": coord , "source": source})


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MapWidget()
    w.show()
    sys.exit(app.exec_())

main.qml

import QtQuick 2.11
import QtPositioning 5.11
import QtLocation 5.11

Rectangle {
    id:rectangle
    width: 640
    height: 480
    Plugin {
        id: osmPlugin
        name: "osm"
    }
    property variant locationTC: QtPositioning.coordinate(44.951, -93.192)
    Map {
        id: map
        anchors.fill: parent
        plugin: osmPlugin
        center: locationTC
        zoomLevel: 10
        MapItemView{
            model: markermodel
            delegate: MapQuickItem {
                coordinate: position_marker
                anchorPoint.x: image.width
                anchorPoint.y: image.height
                sourceItem:
                    Image { id: image; source: source_marker }
            }
        }
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.