I have a vector layer, populated with points, and I want to programmatically add to this layer.
The part related to the geometry works just out of the box, but I was having trouble with adding attribute values to the new features.
The problem is, when I add a new feature to the layer, I do not manage to specify fields. The feature would complain on exceptions.KeyError
.
featureList = []
## now add the computed points to the layer
for p in [p for p in points.values() if p['computed']]:
x, y = p['coordinates']
feature = QgsFeature()
layerPoint = transf.transform(QgsPoint(x, y))
feature.setGeometry(QgsGeometry.fromPoint(layerPoint))
feature['id'] = p['id']
featureList.append(feature)
layer.dataProvider().addFeatures(featureList)
layer.commitChanges()
And before you ask, obviously I'm sure it's the feature['id']
which is giving trouble, not the p['id']
.
So the short version of the question was "how do I specify fields of a feature before it was ever part of a layer?"