This is an independent followup from my previous question: QGIS Python generate index field

I have two files (points.shp, polylines.shp), each with a variable amount of sublayers of the given geometry type.

I need to add a simple incremental index to each of these sublayers: Add a field, and fill it with an increasing, unique integer. Shouldn't be too hard, but I do get more index fields than I desire:

It might be related to the fact that each layer is not an actual individual file, but instead has a source path such as this:

  • polylines.shp|layerid=0|subset=Layer = 'pathways'
  • polylines.shp|layerid=0|subset=Layer = 'hedgerows'
  • points.shp|layerid=0|subset=Layer = 'trees'

For each file:

  • The first layer to be processed gets a new index field, and the integer values as intended.
  • The second layer gets the index field with the values correctly, but also gets an index_1 field with NULL values.
  • The second layer gets the index field correct, and gets index_1 and index_2 with NULL values.
  • This continues for every added layer, with the last ending up with dozens of new empty fields (index21 in my case) added.

Why does this happen? How can I prevent it?

This is the processing script:

##input_layers=multiple vector

from qgis.core import *
from PyQt4.QtCore import *

def add_index_to_layer(layer):
    fieldindex = layer.fieldNameIndex("index")
    if fieldindex >= 0:
        print "Layer " + layer.name() + " already has an index field"
        return False
    layer.dataProvider().addAttributes([QgsField("index", QVariant.Int)])
    fieldindex = layer.fieldNameIndex("index")
    i = 0
    for feature in layer.getFeatures():
        layer.changeAttributeValue(feature.id(), fieldindex, i)
        i +=1

input_layers = input_layers.split(';')
for i in input_layers:
    layer = processing.getObject(i)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.