QGIS Python Console – Creating Virtual Field

pyqgisqgisqgis-python-consolevirtual-field

I would like to create a new virtual field with a specific expression (like 2*"ID") on an existing layer. Is it possible to do so from the Python console?

I've tried using addExpressionField followed by updatefields as suggested in a similar question (Creating Virtual Field in QGIS Python Console) but when I manually check my layer fields from QGIS, nothing changed.

Best Answer

Try to get the addExpressionField() method from the QgsVectorLayer class with this:

from qgis.utils import iface
from qgis.core import QgsVectorLayer, QgsField
from PyQt5.QtCore import QVariant

layer = iface.activeLayer()

layer.startEditing()
field = QgsField('twoTimesID', QVariant.String)
layer.addExpressionField(' 2 * "id" ', field)
layer.commitChanges()

References:

Related Question