我正在尝试将多个地理坐标与地图中的折线连接起来。坐标存储在模型 (QAbstractListModel) 类中,我可以在其中修改(删除和添加)C++ 中的坐标。
简单地显示每个坐标的标记就可以了,但是当我将它们与折线连接并从模型中删除一些现有坐标时,折线不会更新。
map.qml
import QtQuick 2.0
import QtLocation 5.6
import QtPositioning 5.6
Item {
width: 512
height: 512
visible: true
id: mainWindow
Map { //our map
anchors.fill: parent
id: map
plugin: mapPlugin
zoomLevel: 14
focus: true
Plugin {
id: mapPlugin
name: "osm"
}
MapItemView {
model: markerModel
delegate: mapcomponent
}
MapItemView {
model: markerModel
delegate: MapPolyline {
antialiasing: true
line.color: "darkBlue"
line.width: 3
path: pathRole
}
}
Component {
id: mapcomponent
MapQuickItem{
id: marker
coordinate: positionRole
sourceItem: Image{
id: markerimage
width: 20
height: 30
source: "qrc:/marker.png"
}
anchorPoint.x: markerimage.width / 2
anchorPoint.y: markerimage.height
}
}
MouseArea {
anchors.fill: parent
onClicked: {
var coord = parent.toCoordinate(Qt.point(mouse.x,mouse.y))
markerModel.addMarker(coord)
}
}
}
}
标记模型.h它存储坐标
class MarkerModel : public QAbstractListModel {
Q_OBJECT
public:
using QAbstractListModel::QAbstractListModel;
enum MarkerRoles{positionRole = Qt::UserRole, pathRole};
Q_INVOKABLE void addMarker(const QGeoCoordinate &coordinate) {
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_coordinates.append(coordinate);
endInsertRows();
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override {
Q_UNUSED(parent)
return m_coordinates.count();
}
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override {
if(row + count > m_coordinates.count() || row < 0)
return false;
beginRemoveRows(parent, row, row+count-1);
for(int i = 0; i < count; ++i)
m_coordinates.removeAt(row + i);
endRemoveRows();
return true;
}
bool removeRow(int row, const QModelIndex &parent = QModelIndex()) {
return removeRows(row, 1, parent);
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override {
if (index.row() < 0 || index.row() >= m_coordinates.count())
return QVariant();
if(role == Qt::DisplayRole)
return QVariant::fromValue(index.row());
if(role == MarkerModel::positionRole)
return QVariant::fromValue(m_coordinates[index.row()]);
if(role == MarkerModel::pathRole) {
QVariantList coordlist;
for(auto &geocoord : m_coordinates)
coordlist << QVariant::fromValue(geocoord);
return coordlist;
}
return QVariant();
}
QHash<int, QByteArray> roleNames() const {
QHash<int, QByteArray> roles;
roles[positionRole] = "positionRole";
roles[pathRole] = "pathRole";
return roles;
}
private:
QList<QGeoCoordinate> m_coordinates;
};
显示我的问题的 gif:
在删除模型中的行时我是否遗漏了某些内容?有没有办法强制 qml 使用模型中的全新数据渲染折线?