[GIS] How to add a new feature to a layer

actionspyqgisqgis

I have a table with three attributes [field1, field2, field3].

I'm trying to insert a new feature to this table by defining field2 and field3 only.

lyr = QgsMapLayerRegistry.instance().mapLayer('layer')

new_feat = QgsFeature()

new_feat.setAttribute(1,"text1")
new_feat.setAttribute(2,"text2")

lyr.dataProvider().addFeatures([new_feat])
lyr.commitChanges()

It seems that I have a problem with the index in the setAttribute.
What am I missing?

Best Answer

You must declare the feature's fields before being able to use them:

lyr = QgsMapLayerRegistry.instance().mapLayer('layer')
fields = lyr.pendingFields()   
new_feat = QgsFeature(fields)

new_feat.setAttribute(1,"text1")
new_feat.setAttribute(2,"text2")

lyr.dataProvider().addFeatures([new_feat])
lyr.commitChanges()
Related Question