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

时间:2016-03-21 20:42:03

标签: python pyqt qml pyqt5 qtpositioning

我使用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代码的示例。我已将此QML文件作为UI文件中的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完成。

1 个答案:

答案 0 :(得分:1)

如果要使用QML与C ++ / Python进行交互,最好将某些对象暴露给QML,以便将C ++ / Python的数据传输到QML,因为后者具有不同的生命周期。

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

main.py

pg

main.qml

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_())

enter image description here