When I try to calculate a new field with:
idx = layer.fieldNameIndex(attributeName)
I receive the following error:
AttributeError: 'QgsVectorLayer' object has no attribute 'fieldNameIndex'
What ́s the problem? I'm using QGIS 3.0.1 64x in Windows.
asked Apr 18, 2018 at 14:09
-
Please, do not forget about "What should I do when someone answers my question?"Taras– Taras ♦2022年11月19日 11:25:30 +00:00Commented Nov 19, 2022 at 11:25
2 Answers 2
In PyQGIS 3
Use one of the following methods from the QgsFields
class:
-
layer = iface.activeLayer() layer_fields = layer.fields() field_index = layer_fields.indexFromName("FIELD_NAME")
-
layer = iface.activeLayer() layer_fields = layer.fields() field_index = layer_fields.lookupField("FIELD_NAME")
-
layer = iface.activeLayer() layer_fields = layer.fields() field_index = layer_fields.indexOf("FIELD_NAME")
answered Jun 20, 2018 at 9:45
You need to access it via the fieldNameIndex()
method of the QgsVectorDataProvider
class:
layer = iface.activeLayer()
idx = layer.dataProvider().fieldNameIndex(attributeName)
answered Apr 18, 2018 at 14:14
-
How do you do that in the Python console? I'm a noob.Marco– Marco2018年04月18日 16:28:36 +00:00Commented Apr 18, 2018 at 16:28
-
@MarcoUscuchagua - Click on a layer and type
layer = iface.activeLayer()
. Then typeidx = layer.dataProvider().fieldNameIndex("fieldName"). The
self` parameter is mainly used for plugins.Joseph– Joseph2018年04月20日 09:15:20 +00:00Commented Apr 20, 2018 at 9:15 -
The error remains. I think it is a error of QGIS and not of my layer.Marco– Marco2018年04月20日 12:17:35 +00:00Commented Apr 20, 2018 at 12:17
-
@MarcoUscuchagua - What error are you receiving? Is it the same error as in your question?Joseph– Joseph2018年04月20日 12:34:57 +00:00Commented Apr 20, 2018 at 12:34
-
1I found the solution!! The problem was in the Quick Attribution plugin, its reinstallation solved the problem. Thanks @JosephMarco– Marco2018年04月24日 00:42:37 +00:00Commented Apr 24, 2018 at 0:42
Explore related questions
See similar questions with these tags.
lang-py