[Qgis-developer] how to add a new field to an existing layer?

Ricardo Filipe Soares Garcia da ricardo.garcia.silva at gmail.com
Mon Aug 9 08:50:08 EDT 2010


Hello list

How can I add a new field to an existing layer and insert some new
values in it? In the following example, pointLayer refers to an
existing layer, previously created using the memory provider. This
code is creating the new field, but I cannot insert the values in it.
Although it runs without any error, when I look at the layer's
attribute table, the new field is there, but every feature has it as
NULL. By the way, I think this kind of operation would be a nice thing
to go into the pyqgis cookbook
Thanks for your help.
I am trying:

#python code:
provider = pointLayer.dataProvider()
newField = QgsField("channel", QVariant.Double)
provider.addAttributes([newField])
newFieldIndex = provider.fieldNameIndex(newField.name())
#more code
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
feat = QgsFeature()
while provider.nextFeature(feat):
    # more code, calculating the value of the 'channelValue' variable
    feat.addAttribute(newFieldIndex, channelValue)


-- 
___________________________ ___ __
Ricardo Garcia Silva


More information about the Qgis-developer mailing list