QGis二次开发-保存矢量图形和字段

1、首先拿到shp图层

1
QgsVectorLayer *currentLayer = qobject_cast<QgsVectorLayer *>(MainWindow::TheInstance()->getActiveMapCanvas()->currentLayer());

点击并拖拽以移动

2、生成矢量对象

1
2
3
4
5
6
//保存点
QgsPoint point(x,y,z);
//保存线 或面 其中QgsPolyline由QgsPoint 的点集组成
QgsPolyline Poly;
//QgsPolyline往塞点
poly.append(point);

点击并拖拽以移动

3、生成几何对象,如果shp是三维的,hasM和hasZ是必须的,没有这一步会导致图层损坏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//点
QgsGeometry Geo = QgsGeometry::fromPointXY(QgsPointXY(x, y));
if (QgsWkbTypes::hasM(layerWKBType))
{
Geo.get()->addMValue();
}
if (QgsWkbTypes::hasZ(layerWKBType))
{
Geo.get()->addZValue();
}

//线
QgsGeometry Geo = QgsGeometry::fromPolyline(poly);
if (QgsWkbTypes::hasM(layerWKBType))
{
Geo.get()->addMValue();
}
if (QgsWkbTypes::hasZ(layerWKBType))
{
Geo.get()->addZValue();
}
//面
QgsGeometry Geo = QgsGeometry::fromPolyline(poly);
QVector<QgsGeometry> vGeo;
vGeo.append(Geo);
QgsGeometry polygonGeo = Geo.polygonize(vGeo);
if (QgsWkbTypes::hasM(layerWKBType))
{
polygonGeo.get()->addMValue();
}
if (QgsWkbTypes::hasZ(layerWKBType))
{
polygonGeo.get()->addZValue();
}

点击并拖拽以移动

4、添加到图层

1
2
3
4
QgsFeature  Feature = QgsVectorLayerUtils::
createFeature(currentLayer,Geo或者polygonGeo, 属性键值对集合(QgsAttributeMap类型,选填));
currentLayer->addFeature(Feature);
currentLayer->commitChanges();

点击并拖拽以移动

5、设置画布缩放 刷新画布

1
2
3
4
QgsRectangle boundingBox = Geo.boundingBox();
boundingBox.grow(10);
MainWindow::TheInstance()->getActiveMapCanvas()->setExtent(boundingBox);
MainWindow::TheInstance()->getActiveMapCanvas()->refresh();

点击并拖拽以移动

关于如何声明一个属性键值对集合

1
2
3
4
5
//获取当前图层的属性项(字段) 返回的是一个属性项集合
QgsFields fields = currentLayer->fields();
//声明一个map集合,可以多次插入键值对
QgsAttributeMap map;
map.insert(fields.indexOf(属性项的name), QVariant(属性值));

点击并拖拽以移动

关于如何写入属性项(字段)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
QList<QgsField> fieldList;
QgsFields currentLayerFields = currentLayer->fields();
QStringList fields = {你要插入的字段 };

for (int i = 0; i < fields.count(); ++i)
{
//如果该不存在,则插入
if (currentLayerFields.indexFromName(fields.at(i)) == -1)
{
QgsField shpField(fields.at(i), QVariant::String);
fieldList.push_back(shpField);
}
}
QgsVectorDataProvider* vectorProvider = currentLayer->dataProvider();
vectorProvider->addAttributes(fieldList);
currentLayer->updateFields();

点击并拖拽以移动


QGis二次开发-保存矢量图形和字段
http://pla.com/2020/07/01/QGis/QGis二次开发保存-矢量图形和字段/
作者
RenMingchang
发布于
2020年7月1日
许可协议