I am trying to calculate a unique ID field for a vector layer in qgis, using python. I found some code to calculate attribute values, and tried to increment the value in the expression, but it doesn't work – it calculates all feature values as 0. I'm guessing the intial value I set for the expression is what it is reading each time – it doesn't seem to change it inside the loop. Anyone have any ideas? Here is my code:
QgsMapLayerRegistry.instance().addMapLayer(dsslvExplodeLyr)
idx = dsslvExplodeLyr.fieldNameIndex('UniqueID')
eVal = '0'
e = QgsExpression(eVal)
e.prepare(dsslvExplodeLyr.pendingFields())
dsslvExplodeLyr.startEditing()
for f in dsslvExplodeLyr.getFeatures():
num = int(eVal)
num = num + 1
eVal = str(num)
f[idx] = e.evaluate(f)
dsslvExplodeLyr.updateFeature(f)
dsslvExplodeLyr.commitChanges()
I should mention I've also tried '$rownum' for the expression as that works in the field calculator gui but it also just gives a value of 0.
Best Answer
This code works well (fillFields function) and it is not requiered the start editing operating.
I used your nomenclature for the layer name (dsslvExplodeLyr; a point vector layer) and its field name (UniqueID). The script changed aleatory values between -10 and 10 into this field to integer values between 0-24.
Before running the code in the Python Console:
After running the code