In a vector layer table there are two fields F1 and F2 with float type. I want to multiply these fields and insert results to new field F3.
In below code new field created but without any value. What is problem?
layer = iface.activelayer()
F1 = self.ui.cBox_Width.currentText()
F2 = self.ui.cBox_Length.currentText()
new_Field = "F3"
provider = layer.dataProvider()
caps = provider.capabilities()
idx = provider.fieldNameIndex(new_Field)
try:
if idx == -1:
if caps & QgsVectorDataProvider.AddAttributes:
res = provider.addAttributes([QgsField(new_Field, QVariant.Double)])
except:
return False
layer.startEditing()
bufferfield = layer.fieldNameIndex('buffer_km')
formula = QgsExpression("\"F1\" * \"F2\"")
formula.prepare(layer.pendingFields())
for f in layer.getFeatures():
f[idx] = formula.evaluate(f)
layer.updateFeature(f)
layer.updateFields()
layer.commitChanges()
F1andF2with the actual field names in the lineformula = QgsExpression(str(F1) + '*' + str(F2))? (i.e.formula = QgsExpression('fieldName1 * fieldName2)) – Joseph Oct 27 '17 at 12:32F1andF2with field names and but it didn't work :( – HMadadi Oct 27 '17 at 13:13doubleand when I test the code with another field with type ofqlonglongit works. But when I useField CalculatorGUI it works forF1andF2withdoubletype.What is problem in this code for act ondoubletype values? – HMadadi Oct 27 '17 at 13:36