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.
1 Answer 1
Try to get the addExpressionField()
method from the QgsVectorLayer
class with this:
from qgis.utils import iface
from qgis.core import QgsField
from qgis.PyQt.QtCore import QVariant
layer = iface.activeLayer()
field = QgsField('twoTimesID', QVariant.String)
layer.addExpressionField(' 2 * "id" ', field)
References:
Explore related questions
See similar questions with these tags.