I want to store values from a virtual field to a static field (the file will be used externally and I need those calculated values from the virtual field hard coded). My idea was to write a python code snippet and add this to the Project macros saveProject(), so when I close QGIS, after working on the layer, the virtual field would be copied to a static field for outside use. I'm new to Python an have come so far:

# Import required modules
from qgis.core import edit

layer = QgsProject.instance().mapLayersByName('my_trails_z_epsg3857')[0]
# index of target field
idx = layer.fields().indexFromName('description')

with edit(layer):
    for feat in layer.getFeatures():
        # write new_values from virtual field <CP_description> to target field
        new_value = feat['CP_description']
        layer.changeAttributeValue(feat.id(), idx, new_value)

However, after running this code in the PY Console for testing, no new values are written to the target field..

  • Your code works when I test it. A couple of things to check: Is your description field the right data type? If you accidentally created an integer field, inserting strings will result in NULL values. Is the layer already in edit mode? If so, an assertion error will be thrown by with edit and the code within the block will not run.
    – Matt
    Apr 14, 2023 at 16:04
  • thanks @Matt for trying the code! I'll check if there is some issues with the values maybe (data types are good)..
    – Kay
    Apr 15, 2023 at 14:25
  • @Matt I reckon that it has to do with some buggy behavior due to the feature values, which is very long text (>255 chars), with emojis and some html tags.. The File I'm working on is a geojson file. The field type/length of the target field is string/1000..
    – Kay
    Apr 17, 2023 at 12:30
  • If you set the field length to 0 then it will be unlimited, not sure if that will fix it, but worth a try.
    – Matt
    Apr 17, 2023 at 12:54
  • @Matt i had field length set to 0, too.. But it keeps behaving buggy (not writing any values, all NULLs). I don't get it.
    – Kay
    Apr 18, 2023 at 8:43


Your Answer

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

Browse other questions tagged or ask your own question.