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.