2

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)

1 Answer 1

1

Variables are not supported inside the expression. The doc mentions numbers, strings and column name only.

However you can build the expression with the values read from your variable.

ratio_roche=0.2
exp_Deb_meuble = QgsExpression( str(ratio_roche) + ' *((Prof_am*Prof_av)/2)*LargTranch*$length ' )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.