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

Martin Dobias wonder.sk at gmail.com
Wed Aug 11 03:10:00 EDT 2010


On Wed, Aug 11, 2010 at 1:49 AM, Ricardo Filipe Soares Garcia da
<ricardo.garcia.silva at gmail.com> wrote:
>
> 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
>    values = {feat.id() : {newFieldIndex: QVariant(channel)}}
>    provider.ChangeAttributeValues(values)

Btw. for a better performance, it is good to only fill the new values
into the 'values' dictionary within the 'while' cycle. Afterwards you
can run changeAttributeValues() once to modify all features. Anyway if
you do not work with lots of features, it is not so imporant.

Martin


More information about the Qgis-developer mailing list