[GIS] How to get the field index of the new layer in the script using Python

fields-attributespythonqgisqgis-plugins

I am trying to use layer.changeAttributeValue(fid, fieldIndex, value) to add values to a field in QGIS

Basically, I'm creating a plugin which will, if a checkbox is ticked, create a new field, then iterate through the dataset, filling that field with the x (easting) coordinate of each point (I also have another checkbox for the same for the y coordinate). As such, I cannot set the field index beforehand because I don't know which will be ticked.

So – how can I get the field index of the new layer in my script using Python?

Also (sorry, I'm new to this), how can I get the fid of the current feature as I iterate through the dataset?

Best Answer

int QgsVectorDataProvider::fieldNameIndex (const QString & fieldName) const

Returns the index of a field name or -1 if the field does not exist.

http://qgis.org/api/2.0/classQgsVectorDataProvider.html#a10263dbd16e19d7aa146a818ac002266

Related Question