12

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.

1

2 Answers 2

19

In PyQGIS 3

Use one of the following methods from the QgsFields class:

  1. indexFromName()

    layer = iface.activeLayer()
    layer_fields = layer.fields()
    field_index = layer_fields.indexFromName("FIELD_NAME")
    
  2. lookupField():

    layer = iface.activeLayer()
    layer_fields = layer.fields()
    field_index = layer_fields.lookupField("FIELD_NAME")
    
  3. indexOf()

    layer = iface.activeLayer()
    layer_fields = layer.fields()
    field_index = layer_fields.indexOf("FIELD_NAME")
    
7

You need to access it via the fieldNameIndex() method of the QgsVectorDataProvider class:

layer = iface.activeLayer()
idx = layer.dataProvider().fieldNameIndex(attributeName)
8
  • How do you do that in the Python console? I'm a noob.
    – Novvier
    Apr 18, 2018 at 16:28
  • @MarcoUscuchagua - Click on a layer and type layer = iface.activeLayer(). Then type idx = layer.dataProvider().fieldNameIndex("fieldName"). The self` parameter is mainly used for plugins.
    – Joseph
    Apr 20, 2018 at 9:15
  • The error remains. I think it is a error of QGIS and not of my layer.
    – Novvier
    Apr 20, 2018 at 12:17
  • @MarcoUscuchagua - What error are you receiving? Is it the same error as in your question?
    – Joseph
    Apr 20, 2018 at 12:34
  • 1
    I found the solution!! The problem was in the Quick Attribution plugin, its reinstallation solved the problem. Thanks @Joseph
    – Novvier
    Apr 24, 2018 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.