3

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

5

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:

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.