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?