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


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



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?


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.

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.