Is there any example about how to create a virtual field and subsequently change the attribute of a non-virtual field without wiping out the virtual field? Both are required to be done in the Python Console.

  • 2
    Good question as I use Virtual Fields quite a lot. I also noticed the Field Calculator in QGIS Modeler doesn't have an option to insert virtual fields so it would be interesting to see how to achieve this via the console.
    – Joseph
    Apr 28, 2015 at 8:57

1 Answer 1


When you have a variable layer that is a reference to a vector layer you need

  • to specify the field definition

  • add the new field with an expression

     field = QgsField('twoTimesA', QVariant.LongLong)
     layer.addExpressionField(' 2 * "A" ', field)

You can now modify an attribute and when you query the layer next time the virtual field will be updated.

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.