我想在QML Map应用程序中动态添加/删除/编辑MapPolygon
。我还有其他一些创建多边形的工作(文件导出/导入等),所以我认为我应该将MapItemView
与C ++模型结合使用多边形数据。
我尝试使用基于QObject的对象创建自己的模型:
对象:
class MODELSHARED_EXPORT Polygon : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<QGeoCoordinate> coordinates READ coordinates WRITE setCoordinates NOTIFY coordinatesChanged)
public:
explicit Polygon(QObject *parent = nullptr);
QList<QGeoCoordinate> coordinates() const;
void setCoordinates(QList<QGeoCoordinate> coordinates);
signals:
void coordinatesChanged(QList<QGeoCoordinate> coordinates);
public slots:
void addCoordinate(const QGeoCoordinate & coordinate);
private:
QList<QGeoCoordinate> m_coordinates;
};
型号:
class MODELSHARED_EXPORT PolygonModel : public QAbstractListModel
{
...
QVariant data(const QModelIndex &index, int role) const override
{
if(index.row() >= 0 && index.row() < rowCount()) {
switch (role) {
case CoordinatesRole:
return QVariant::fromValue(m_data.at(index.row())->coordinates());
}
}
return QVariant();
}
public slots:
void addArea()
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_data.append(new Polygon(this));
endInsertRows();
}
void addPolygonCoordinate(const QGeoCoordinate &coordinate, int index)
{
if(index == -1) {
index = rowCount() - 1;
}
m_data.at(index)->addCoordinate(coordinate);
dataChanged(this->index(0), this->index(rowCount() - 1));
qDebug() << "Adding coordinate..." << coordinate;
}
private:
QList<Polygon*> m_data;
};
和QML:
MapItemView {
id: AreaView
delegate: AreaPolygon {
path: coordinates
}
model: cppPolygonModel
}
AreaPolygon.qml
MapPolygon {
id: areaPolygon
border.width: 1
border.color: "red"
color: Qt.rgba(255, 0, 0, 0.1)
}
但是不幸的是,多边形没有出现在地图上(当坐标成功添加到对象QList属性中时)。我认为从视图中看不到Object QList附加组件,因此MapItemView不会刷新。
还有更好的选择吗?也许我应该使用QGeoPolygon
对象的模型? (如何?)
答案 0 :(得分:1)
您必须返回QVariantList
而不是QList<QGeoCoordinate>
:
if(index.row() >= 0 && index.row() < rowCount()) {
switch (role) {
case CoordinatesRole:
QVariantList coorvariant;
for(const QGeoCoordinate & coord: m_data.at(index.row())->coordinates()){
coorvariant.append(QVariant::fromValue(coord));
}
return coorvariant;
}
}