0

using python editor in QGIS, I want to update a field based on a variable calculated previously in my script (x for this example). I have used the code with success when using an expression based on other fields e.g:

expression = QgsExpression("field1||'_'||field2")

but I can't get it to work when the expression is based on a variable, not a field.

x = 5 
id_new_col= layer.dataProvider().fieldNameIndex("field") 
expression = QgsExpression("x") 
context = QgsExpressionContext() 
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer)) 
for f in layer.getFeatures():
        with edit(layer):
            context.setFeature(f)
            f['field'] = expression.evaluate(context)
            layer.updateFeature(f)

This results in an empty field.

How can I call the variable into the field calculator expression?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
JUNGLE
  • 510
  • 2
  • 10
  • 2
    Where do you use this script, in "Function Editor" or "Python Editor"? Please add the whole script. It is not clear what layer is. It is a vector layer, of course. But where does it come from? – Kadir Şahbaz May 14 '21 at 01:56
  • 2
    And, x in x = 5 and x in QgsExpression("x") are not related., The former is a python variable, the latter indicates a field in the layer, I guess. – Kadir Şahbaz May 14 '21 at 02:30

0 Answers0