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.

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked May 9, 2022 at 11:05

1 Answer 1

6

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:

answered May 9, 2022 at 11:16
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.