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?

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
Frank
  • 337
  • 1
  • 5

1 Answers1

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.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
  • It works, thank you! What a quick and easy solution (I am still a beginner with python and qgis). – Frank Nov 23 '16 at 01:51
  • No worries, and keep learning. Besides the PyQGIS Cookbook, you could find these resources interesting: http://gis.stackexchange.com/questions/114301/how-to-get-into-the-python-api-of-qgis/188707#188707 – Germán Carrillo Nov 23 '16 at 02:02