Monday, 6 November 2017

pyqgis - QGIS Python generate index field


I have some shapefiles for which I need to generate an index(int) field.


I tried using this function:


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)])
layer.updateFields() # no idea if this is actually needed?
fieldindex = layer.fieldNameIndex("index")
i = 0
layer.startEditing()
for field in layer.fields():
print field.name() # this shows the field "index" indeed exists
for feature in layer.getFeatures():
print feature.id(), feature["index"]
feature.setAttribute("index", i)

# this shows the value is being correctly set at this point
print feature.id(), feature["index"]
i +=1
layer.commitChanges()

The function runs just fine, the various print functions also show everything works as expected (values being set correctly).


However, when verifiyng by looking at the attribute table, the index field is created, but it always is empty/NULL.


Does anyone have an idea about what is going on? Are some of the changes pending where I expect them to be commited already? I thought layer.startEditing() and layer.commitChanges() would properly encapsulate feature field changes?


I am working with QGIS 2.18.0, and the script is created as a processing script.



Answer




Try replacing this line:


feature.setAttribute("index", i)

with this:


layer.changeAttributeValue(feature.id(), layer.fieldNameIndex("index"), i)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...