Модель MapPolyline не обновляется в MapviewPython

Программы на Python
Anonymous
Модель MapPolyline не обновляется в Mapview

Сообщение Anonymous »

Я хочу создать модель MapPolyline в PySide6, которая прокладывает путь в MapView.
Однако, когда пути к модели. MapView не обновляется после установки rootContext.
Вот мой код.

Код: Выделить всё

# 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')
Первая полилиния рисуется моделью, но после добавления модели в корневой контекст она перестает обновляться.
Я думаю, проблема заключается в функции addPath< /p>

Код: Выделить всё

@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.

Подробнее здесь: https://stackoverflow.com/questions/786 ... in-mapview

Вернуться в «Python»