I have to do a script that adds a field and changes attributes values utilising an expression so i use QgsExpression.
When i put a expression in QgsExpression where there is only 'field name' it works QgsExpression( """ ((Prof_am*Prof_av)/2)*LargTranch*$length """ )
, but when i put in the expression a variable it doesn't work ' (ratio_roche)*((Prof_am*Prof_av)/2)*LargTranch*$length '
below is my script after adding new fields:
Features = layer.getFeatures()
for feat in Features:
if feat[field_Prof_am_index]<feat[field_ProfRocher_index] and feat[field_Prof_av_index]<feat[field_ProfRocher_index]:
#terrain 100% meuble
exp_Deb_meuble = QgsExpression( """ ((Prof_am*Prof_av)/2)*LargTranch*$length """ )
exp_Deb_meuble.prepare(layer.pendingFields())
feat[field_Deb_meuble_index] = exp_Deb_meuble.evaluate(feat)
feat[field_Deb_roche_index] = 0
layer.updateFeature(feat)
else:
#terrain en partie rocheux
#ratio de la partie rocheuse
ratio_roche=0.2
#evaluer quantite de la partie meuble
exp_Deb_meuble = QgsExpression( ' (ratio_roche)*((Prof_am*Prof_av)/2)*LargTranch*$length ' )
exp_Deb_meuble.prepare(layer.pendingFields())
feat[field_Deb_meuble_index] = exp_Deb_meuble.evaluate(feat)
#evaluer quantite de la partie rocheuse
exp_Deb_roche = QgsExpression( ' (1-ratio_roche)*((Prof_am*Prof_av)/2)*LargTranch*$length ' )
exp_Deb_roche.prepare(layer.pendingFields())
feat[field_Deb_roche_index] = exp_Deb_roche.evaluate(feat)
layer.updateFeature(feat)