4

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

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)
7
  • Thanks Sir, your code is working well. Jan 11 at 7:44
  • Sure, can you please tell me how to save this 'temp layer' to a shapefile. Jan 11 at 7:54
  • Please check this answer. Jan 11 at 7:56
  • exec(open('C:/Users/user/AppData/Local/Temp/tmp0hckdeoh.py'.encode('utf-8')).read()) Traceback (most recent call last): File "C:\PROGRA~1\QGIS31~1.14\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 20, in <module> TypeError: QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any overloaded call: overload 1: argument 4 has unexpected type 'NoneType' overload 2: argument 4 has unexpected type 'NoneType' overload 3: argument 3 has unexpected type 'str' Jan 11 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.