1、首先拿到shp图层
QgsVectorLayer *currentLayer = qobject_cast<QgsVectorLayer *>(MainWindow::TheInstance()->getActiveMapCanvas()->currentLayer());
2、生成矢量对象
//保存点
QgsPoint point(x,y,z);
//保存线 或面 其中QgsPolyline由QgsPoint 的点集组成
QgsPolyline Poly;
//QgsPolyline往塞点
poly.append(point);
3、生成几何对象
//点
QgsGeometry Geo = QgsGeometry::fromPointXY(QgsPointXY(x, y));//线
QgsGeometry Geo = QgsGeometry::fromPolyline(poly);
//面
QgsGeometry Geo = QgsGeometry::fromPolyline(poly);
QVector<QgsGeometry> vGeo;
vGeo.append(Geo);
QgsGeometry polygonGeo = g.polygonize(vGeo);
4、添加到图层
QgsFeature Feature = QgsVectorLayerUtils::createFeature(currentLayer,Geo或者polygonGeo, 属性键值对集合(QgsAttributeMap类型,选填));
currentLayer->addFeature(Feature);
5、设置画布缩放 刷新画布
QgsRectangle boundingBox = Geo.boundingBox();
boundingBox.grow(10);
MainWindow::TheInstance()->getActiveMapCanvas()->setExtent(boundingBox);
MainWindow::TheInstance()->getActiveMapCanvas()->refresh();
关于如何声明一个属性键值对集合
//获取当前图层的属性项(字段) 返回的是一个属性项集合
QgsFields fields = currentLayer->fields();
//声明一个map集合,可以多次插入键值对
QgsAttributeMap map;
map.insert(fields.indexOf(属性项的name), QVariant(属性值));
关于如何写入属性项(字段)
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();