6

I need a temporary layer with the geometry created from selected features for a processing tool. The temporary layer is created but the geometry is missing. The attribute table is blank.

enter image description here

But when I printed the geometry it's showing on console.

enter image description here

Below is the code I am using:

layer = iface.activeLayer() # layer which has a selection 
feat = layer.selectedFeatures()
fields = layer.fields()

selection = QgsVectorLayer('Point', 'temp', 'memory') dp = selection.dataProvider() dp.addAttributes(fields) feats = selection.selectedFeatures() for feat in feats: geom = feat.geometry() wkt = geom.asPoint() print(wkt) selection.commitChanges() selection.updateExtents()

QgsProject.instance().addMapLayer(selection) temp = QgsVectorLayer("D:\satya\cp.shp", "premises", "ogr")

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
Satya Dalei
  • 117
  • 5

1 Answers1

5

You try to select the features in the newly created layer and you use commitChanges without startEditing. addAttributes adds the fields' definition to the target layer. It doesn't add the features' attrribute values.

You can use this script:

layer = iface.activeLayer() # layer which has a selection 
feats = layer.selectedFeatures()
fields = layer.fields()

crs = layer.crs().authid() selection = QgsVectorLayer('Point?crs=' + crs, 'temp', 'memory') dp = selection.dataProvider() dp.addAttributes(fields) selection.updateFields()

for feat in feats: feature = QgsFeature(layer.fields()) feature.setAttributes(feat.attributes()) feature.setGeometry(feat.geometry()) dp.addFeatures([feature]) dp.updateExtents()

QgsProject.instance().addMapLayer(selection)

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389