6

I've got a question regarding the copying of features from a layer to a new layer while keeping all former attribute data. All this I want to do with PyQGIS (eventually the code will expand more).

So far I got the following code:

from PyQt4.QtCore import *

lyr = iface.activeLayer()
vl = QgsVectorLayer("Point", "temporary_points", "memory")
pr = vl.dataProvider()

pr.addAttributes([QgsField("field_1", QVariant.String),QgsField("field_2", QVariant.String),QgsField("field_3", QVariant.String),QgsField("field_4", QVariant.String)])

vl.startEditing()

outFeat = QgsFeature()
for feat in lyr.getFeatures():
    attrs = feat.attributes()
    if attrs[2] == 'pvs':
        outFeat.setGeometry(feat.geometry())
        outFeat.setAttributes(feat.attributes())
        print attrs[4]
        pr.addFeatures([outFeat])

vl.commitChanges()

QgsMapLayerRegistry.instance().addMapLayer(vl) 

So far, everything works fine. However, I do not like it that I have to "hard-copy" every attribute field in the pr.addAttributes section.

What I would like to do is append all the attributes that are present in the source layer ('lyr') to the new "temporary_points" layer. Is this possible?

1 Answer 1

9

You can get the fields definition from source layer and pass it to your new memory layer in this way:

pr.addAttributes( sourceLayer.fields() )

That's all you need.

2
  • It works, thank you! What a quick and easy solution (I am still a beginner with python and qgis).
    – Frank
    Commented Nov 23, 2016 at 1:51
  • No worries, and keep learning. Besides the PyQGIS Cookbook, you could find these resources interesting: gis.stackexchange.com/questions/114301/… Commented Nov 23, 2016 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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