[GIS] How to add a column/feature with PyQGIS 2.x

errorpyqgispythonqgisqgs

I'm using PyQgis 2.2 and I'm creating a plugin.
I want to add one feature/column to a shapefile. But I get error..

I've tried to do this as it's shown in Cookbook:

 if caps & QgsVectorDataProvider.AddFeatures:
     feat = QgsFeature()
     feat.addAttribute(0,"hello")
     feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(123,456)))
     (res, outFeats) = layer.dataProvider().addFeatures( [ feat ] )

but I only get error:

 AttributeError: 'QgsFeature' object has no attribute 'addAttribute'

Best Answer

It seems you are reading an old version of the PyQGIS Cookbook.

Try with the addAttributes method of the layer provider, as indicated in the latest PyQGIS Cookbook. Specifically:

if caps & QgsVectorDataProvider.AddFeatures:
    res = layer.dataProvider().addAttributes([QgsField("id",  QVariant.Int), QgsField("mytext", QVariant.String)])
    feat = QgsFeature()
    feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(123,456)))
    feat.setAttributes([0, "hello"])
    (resAddFeat, outFeats) = layer.dataProvider().addFeatures( [ feat ] )
Related Question