7

Im using QGIS 3.18.2 and I want to get the expression string of a virtual field in PyQGIS.

QgsVectorLayer.expressionField() is supposed to return the expression string. It takes the index (index: int) of the expression (virtual) field as argument.

Let's say I have a virtual field named expr_f_1. When I call QgsVectorDataProvider.fieldNameIndex("expr_f_1") it returns -1, which corresponds to a missing field. This seems to happen for virtual fields in general. They also don't appear in QgsVectorDataProvider.fieldNameMap().

How do I get the correct index of a virtual field, in order to pass it to QgsVectorLayer.expressionField() to return the corresponding expression string?

9

Use layer.fields().indexFromName("expr_f_1").

Because:

Virtual fields are a pure QGIS concept. The data provider does not know the slightest bit about their existence. Virtual fields are just put "on top of" the real data, their values are temporarily regenerated by QGIS every time they are required somewhere.

You may want to read Matthias's answer for more information.

layer = iface.activeLayer()
i = layer.fields().indexFromName("expr_f_1")
print(layer.expressionField(i))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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