I am want to create a MapPolyline model in PySide6, which plots a path on a mapView. However when paths to the model. The MapView does not update after setting the rootContext. Here is my code.
# 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')
The first Polyline is drawn by the Model, but after adding the model to the rootContext, it stops updating itself. I thing the Problem lies in in the addPath-function
@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
in my PathModel.
I found the solution for some reason the Repeater is not drawing multiple MapPolylines. I replaced it with with a 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;
}
}
}