13

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.

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Apr 18, 2018 at 14:09
1

2 Answers 2

21

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")
    
Taras
35.8k5 gold badges77 silver badges151 bronze badges
answered Jun 20, 2018 at 9:45
7

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

layer = iface.activeLayer()
idx = layer.dataProvider().fieldNameIndex(attributeName)
Taras
35.8k5 gold badges77 silver badges151 bronze badges
answered Apr 18, 2018 at 14:14
8
  • How do you do that in the Python console? I'm a noob. Commented 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. Commented Apr 20, 2018 at 9:15
  • The error remains. I think it is a error of QGIS and not of my layer. Commented Apr 20, 2018 at 12:17
  • @MarcoUscuchagua - What error are you receiving? Is it the same error as in your question? Commented 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 Commented Apr 24, 2018 at 0:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.