我想在 PySide6 中创建一个 MapPolyline 模型,它在地图视图上绘制一条路径。 但是,当路径指向模型时。设置 rootContext 后,MapView 不会更新。 这是我的代码。
# Path.py
from PySide6.QtCore import QObject, Signal
from PySide6.QtPositioning import QGeoCoordinate
class Path(QObject):
def __init__(self, path : list[QGeoCoordinate] = None, color : str = None):
super(Path, self).__init__()
self.path = path
self.color = color
def __len__(self):
return len(self.path)
def __iter__(self):
return iter(self.path)
def addPoint(self, point):
self.path.insert(len(self.path), point)
def changeColor(self, color):
self.color = color
def getColor(self):
return self.color
def getPath(self):
return self.path
#PathModel.py
from Path import Path
from PySide6.QtCore import Qt, QAbstractListModel, QModelIndex, QByteArray, Slot
from PySide6.QtPositioning import QGeoCoordinate
class PathModel(QAbstractListModel):
ColorRole = Qt.UserRole + 1
PathRole = Qt.UserRole + 2
def __init__(self, paths: list[Path] = None):
super().__init__()
self._paths = paths or []
def data(self, index, role):
if not index.isValid():
return None
path = self._paths[index.row()]
if role == self.ColorRole:
return path.getColor()
if role == self.PathRole:
return path.getPath()
return None
def rowCount(self, parent=QModelIndex()):
return len(self._paths)
def roleNames(self):
roles = super().roleNames()
roles[self.ColorRole] = QByteArray(b'color')
roles[self.PathRole] = QByteArray(b'path')
return roles
@Slot(result=bool)
def addPath(self, df, color):
self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
currentPath = []
for i in range(len(df.index)):
point = df.iloc[i]
currentPath.append(QGeoCoordinate(point['Latitude'], point['Longitude']))
self._paths.append(Path(currentPath, color))
self.endInsertRows()
print(f"Paths added: {self._paths}")
return True
// MapControl.qml
import QtCore
import QtLocation
import QtPositioning
Rectangle {
Plugin {
id: mapView
name: "osm"
PluginParameter {
name: "osm.mapping.custom.host"
value: "https://tile.openstreetmap.org/"
}
}
MapView {
id: view
anchors.fill: parent
map.plugin: mapView
map.activeMapType: map.supportedMapTypes[map.supportedMapTypes.length - 1]
Repeater {
parent: view.map
model: pathModel
delegate: MapPolyline {
line.width: 5
line.color: model.color
path: {
var pathPoints = model.path;
console.log("Path points:", pathPoints);
return pathPoints;
}
}
}
}
}
#MainWindow.py
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.LoadTripsPushButton.clicked.connect(self.LoadDatabase)
self.CurrentTripComboBox.currentTextChanged.connect(self.PlotTrip)
self.trips = pd.DataFrame()
data = {'Latitude': [51.50, 52.52], 'Longitude': [-0.12, 13.40]}
df = pd.DataFrame(data)
self.pathModel = PathModel()
self.pathModel.addPath(df, 'red')
self.QuickMapView.rootContext().setContextProperty('pathModel', self.pathModel)
self.QuickMapView.setSource("MapControl.qml")
data = {'Latitude': [51.50, 52.52], 'Longitude': [48.85, 2.35]}
df = pd.DataFrame(data)
self.pathModel.addPath(df, 'green')
第一条Polyline是由Model绘制的,但是将模型添加到rootContext后,它停止更新自身。 我认为问题出在 addPath 函数中
@Slot(result=bool)
def addPath(self, df, color):
self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
currentPath = []
for i in range(len(df.index)):
point = df.iloc[i]
currentPath.append(QGeoCoordinate(point['Latitude'], point['Longitude']))
self._paths.append(Path(currentPath, color))
self.endInsertRows()
print(f"Paths added: {self._paths}")
return True
在我的 PathModel 中。
由于某种原因,我找到了解决方案,中继器没有绘制多条地图多段线。我用 MapItemView 替换了它
MapItemView {
parent: view.map
model: pathModel
delegate: MapPolyline {
line.width: 5
line.color: model.color
path: {
var pathPoints = model.path;
console.log("Path points:", pathPoints);
return pathPoints;
}
}
}