I want to update a certain field with the current area. What I have tried:

updated_area = iface.addVectorLayer(xx.shp, "", "ogr")

selected_feature = updated_area.selectedFeatures()

for feature in selected_feature:
    feature["area"] = "$area"

I'm not getting any errors, but nor is it updating any fields.

  • 1
    Do you need the python approach ? If not, you can create a virtual field from the field calculator, defined as $area. Otherwise if you want pyqgis to do the evaluation, your feature["area"] field should be something like 'feature.geometry().area()"
    – Kasper
    Jan 23, 2023 at 15:43
  • Yes, unfortunately I do. It's a part of a bigger script. Jan 23, 2023 at 16:57
  • does your shapefile have the area attribute already ? or does it need to be created by the script ?
    – Kasper
    Jan 23, 2023 at 17:03
  • There is a field called area already, but because of some clipping in the script, it needs an update. I wouldn't mind deleting it and adding a new instead, any work-around would do. Jan 23, 2023 at 18:36

1 Answer 1


I've found a way to update the ares, but for what ever reason the numbers are whacked. Like in an unidentified unit.

updated_area = iface.addVectorLayer(xx.shp, "", "ogr")
area_idx = updated_area.fields().lookupField('area')

for f in updated_area.getFeatures():
    area = f.geometry().area()*626336.7007
    updated_area.dataProvider().changeAttributeValues({f.id(): {area_idx: area}})

By multiplying it with 626336.7007 I'm getting the correct numbers, however, but I would like to skip this work around.

  • You haven't told us the CRS of your layer and what is the unit you are expecting.
    – etrimaille
    Jan 24, 2023 at 8:43
  • I'm not sure how to do that. =/ Jan 24, 2023 at 9:10
  • Go in your vector layer properties, the first tab, you have a section "Coordinate Reference System (CRS)". Please edit your question with these info.
    – etrimaille
    Jan 24, 2023 at 9:47
  • If you don't know how to retrieve the CRS of the current layer using QGIS desktop, it seems you have a few more things to know in GIS and QGIS in general before diving into PyQGIS
    – etrimaille
    Jan 24, 2023 at 9:49
  • I meant, I don't know how to do that in code. Using the GUI is not an option. Jan 24, 2023 at 10:14

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.