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?
layeris. It is a vector layer, of course. But where does it come from? – Kadir Şahbaz May 14 '21 at 01:56xinx = 5andxinQgsExpression("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