Adding new features with attributes to an existing layer in PyQGIS?
The first answer I found amounted to copying the fields from an existing feature from the same layer, and feed them to the new feature. It works fine for me, because the code needs at least 3 features to do anything useful, and because earlier in the code I was looping over the features in the layer:
for feature in layer.getFeatures():
# this is a loop I needed anyway
.
.
.
pass
# copy the fields definition from an existing feature
fields = feature.fields()
I am very new to programming in QGIS so I had not yet even seen the page that underdark is linking to in her answer. And even if her answer does not hit the point, the link does help.
I don't need to copy the fields from an existing feature, I can grab them directly from the layer.
fields = layer.fields()
featureList = []
for p in [p for p in points.values() if p['computed']]:
x, y = p['coordinates']
feature = QgsFeature()
# inform the feature of its fields
feature.setFields(fields)
layerPoint = transf.transform(QgsPoint(x, y))
feature.setGeometry(QgsGeometry.fromPoint(layerPoint))
feature['id'] = p['id'] # this now works
featureList.append(feature)
The method you're missing is QgsFeature.setAttributes(). This works for any newly created feature
# add a feature
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(10,10)))
fet.setAttributes(["Johny", 2, 0.3])
pr.addFeatures([fet])
Source: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html