I wondered if I could add virtual fields to the feature tables of a number of polygon layers in a QGIS 3 project (or a geopackage).

As an example, I would like to add the virtual field area (km²) as round($area/1000000, 2) to ten polygon layers stored in a geopackage.

Is there a QGIS way of doing it? If not, any leads if I do this from R? (I don't use Python.)

  • This seems to be a use case to migrate the AutoFields plugin to QGIS 3 and extend it to support Virtual Fields. AutoFields can help to configure a large number of automatic values at once. If you'd like to help to make it possible, feel free to open a feature request at the GitHub repo. Aug 24, 2020 at 13:32

2 Answers 2


This contribution comes a little late, you might have solved it by now, but it might help others stumbling upon this issue. This can be done using the python console in QGIS and the following code:

# define the field you want to add 
fieldDef = QgsField('Your field name', QVariant.Double, 'double', 10, 2)
# define an expression
expression = 'round($area/1000000, 2)'

#loop over the map layers in the interface
for layer in iface.mapCanvas().layers():
    # place an if on the geometry type polygon
    if layer.geometryType() == 2:
        # add the virtual field with the variables set above
        layer.addExpressionField( expression, fieldDef )

    """ quoted out alternative 
    # in case you want a condition on the layer name, get the layer name
    item = layer.name()
    if item[0:3] == 'pol': # tests if the first 3 letters of the layer name is 'pol'
        #add the expression field
        layer.addExpressionField( expression, fieldDef )

Docs: QgsField in the pyQgis doc Credits for the virtual field: How to create a virtual field in QGIS by Python Console?


Open the attribute table of your polygon layer, select field calculator and check the box "create virtual layer". Than just paste the expression to calculate the area. Define a name for your new field and select the field type.

enter image description here

  • Thanks, I knew that. The question is: how to do that to multiple layers or a whole geopackage full of polygons at once?
    – aae
    Aug 24, 2020 at 11:13

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.