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 Poly;
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();
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();
|
