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

Martin Dobias wonder.sk at gmail.com
Tue Aug 10 16:55:19 EDT 2010


Hi Ricardo

On Mon, Aug 9, 2010 at 2:50 PM, Ricardo Filipe Soares Garcia da
<ricardo.garcia.silva at gmail.com> wrote:
> 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.

The problem is that in your code you only modify a local copy of the
data - your change is not propagated to the provider. To actually
modify the data, use something like this:

values = { fid : { attr_1 : QVariant(value_1), attr_2 :
QVariant(value_2) }, ... }
provider.changeAttributeValues( values )

You pass the provider a dictionary where keys are feature IDs, values
are dictionaries of changed attributes (key = attribute index, value =
new attribute value).

> By the way, I think this kind of operation would be a nice thing
> to go into the pyqgis cookbook

Sure, it just needs some time :-)

Regards
Martin


More information about the Qgis-developer mailing list