[Qgis-user] add and populate a field in an existing Vector Layer with python code

smasera stefmase at arpa.piemonte.it
Thu Oct 17 00:17:00 PDT 2013


Hi list,
I wan't to add and populate a field in an existing Vector Layer.
I try to use this code:

layer.dataProvider().addAttributes( [ QgsField("field", QVariant.Int)] )
field_index = layer.fieldNameIndex("field")
print field_index
attrs = {field_index : 123}
# add value for the feature with id = 0
buildings.dataProvider().changeAttributeValues({ 0 : attrs })

But I don't manage to change value.
At the end of the script I found the new field in the Layer Attribute table,
but not the number 123 in the feature 0.
I think the reason is that the fileld creation has to be commit or somethig
like this during the executing code.
In fact, even if I created the field the variable field_index printed is -1
(e.g. non existing field).

I also try to use the classes:
QgsVectorLayer.addattribute()
QgsVectorLayer.changeAttributeValue()
but I don't know how to use it and commit it.

Thanks.

Stefano



--
View this message in context: http://osgeo-org.1560.x6.nabble.com/add-and-populate-a-field-in-an-existing-Vector-Layer-with-python-code-tp5084052.html
Sent from the Quantum GIS - User mailing list archive at Nabble.com.



More information about the Qgis-user mailing list