I want part of my plugin to multiple value of length and add it to table.Basing on this question: How to use QGIS field calculator in python? , I made script that works fine for some filed: I can multiple values of another field (integer) but I can't multiple values ot the 'length' field (double type). I don't know why, but when I'm trying to do : 'length *2' the result is NULL. The 'length' is calculated also inside the plugin.
I'm not sure if the question is understandable, hope code snippets will help:
This is how I calculate length to the 'length' field:
layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:temp_layer") [0]
layer.dataProvider().addAttributes([QgsField("length", QVariant.Double,len = 6, prec = 2)])
layer.updateFields()
idx = layer.fieldNameIndex('length')
layer.startEditing()
for feat in layer.getFeatures():
lengths = feat.geometry().length()
layer.changeAttributeValue(feat.id(), idx, lengths)
layer.commitChanges()
This is how I want to multiple:
layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:temp_layer")[0]
layer.startEditing()
layer.dataProvider().addAttributes([QgsField('n', QVariant.Double,)])
layer.updateFields()
idx = layer.fieldNameIndex('n')
e = QgsExpression ("length * 2")
e.prepare(layer.pendingFields())
for f in layer.getFeatures():
f[idx] = e.evaluate(f)
layer.changeAttributeValue(f.id(),idx, e.evaluate(f))
layer.commitChanges()
I came up with idea that the problem may be that lengths type is float while Qvariant type of field is double. Even if, I don't know how to handle this.
I can multiple 'length' field using standard field calculator, not via Python script and the result is fine.
Any ideas?