QGIS – Creating Virtual Field in QGIS Python Console

pyqgisqgisqgis-python-consolevirtual-field

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.

Best Answer

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.

Related Question