I am trying to get a value created with the expression builder. The expression is in a virtual field. The expression works but when I try to get the value from my python script, it always returns None. Because my python script is a custom form I automatically get the right layer object. This is how I am trying to get the calculated value.

for f in layer.getFeatures():

Maybe I should say that the features are created with the add feature tool and after I identify a feature with the identify tool the script will run.

I figured out that, because my layer is a shapefile, I can't access the value. Only QGIS can see virtual fields, for other layers those fields don't exist.

How can I get the value of a virtual field or can I directly "send" the value to another non-virtual field in QGIS?

  • Can you see the values in the virtual field from the Attribute Table?
    – Joseph
    Dec 7, 2017 at 12:26
  • No, but in the preview from the expression builder.
    – Blinxen
    Dec 7, 2017 at 12:28
  • Hmm it could be a bug. Which QGIS version are you using? I tested this on QGIS 2.18.13 but I also receive NULL values when using the sum aggregate function for a virtual field. There was a bug report issued a while ago which was supposedly fixed in 2.18.10...
    – Joseph
    Dec 7, 2017 at 13:16
  • I am using QGIS 2.18.14
    – Blinxen
    Dec 7, 2017 at 13:19

1 Answer 1


Based on your previous question, you could use a workaround like the following which either creates or updates your virtual field using the calculated sum (i.e. essentially like using the Field Calculator):

from PyQt4.QtCore import QVariant

layer = iface.activeLayer()
exp = QgsExpression('\"name\" = \'marc\'')
request = QgsFeatureRequest(exp)
features = layer.getFeatures(request)
total = 0
for feat in features:
    total += feat['age']

expression = 'CASE WHEN \"name\" = \'marc\' THEN ' + str(total) + ' END'
idx = layer.fieldNameIndex('exprAge')
if idx == -1:
    layer.addExpressionField( expression, QgsField('exprAge', QVariant.Int) )
    layer.updateExpressionField( idx, expression)
  • @Blinxen - Most welcome, glad I helped =)
    – Joseph
    Dec 7, 2017 at 14:08

Your Answer

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

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