PyQGIS Geometry Extraction – Unable to Get Geometry of Temporary Layer Created from Selected Features

featuresgeometrypyqgisqgis

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")

Best Answer

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)
Related Question