I am trying to use the field calculator in a Python script. I use a formula to calculate shortest distance between two polygons (layer_A, layer_B). The formula for the field calculator works well when used directly on layer_A in QGIS. The formula is:


The thing is I can’t figure out how to address the second layer_B in my Python script. I tried using a string to the file path like that:

fomular = '\'length(shortest_line($geometry,geometry(get_feature(\'' + 'path/to/layer_B' + '\',\"fieldname\",attribute(\'fieldname\')))))\''

The formula generates a new field in layer_A, but no distance is calculated. Also, Python gives no error. layer_B seems not to be addressed correctly. What am I doing wrong?

1 Answer 1


Your formula will work if you first make a QgsVectorLayer from the path and add the layers to the canvas. They can be removed immediately after the calculation for clean-up if needs be:

p = QgsProject.instance()

layer_A = QgsVectorLayer('path/to/layer_A', 'layer_A')  # the second argument is the layer name
layer_B = QgsVectorLayer('path/to/layer_B', 'layer_B')  # the second argument is the layer name

# add layers to canvas

formular = "length(shortest_line($geometry, geometry(get_feature('layer_B', 'fieldname',attribute('fieldname')))))"
calculated = processing.run("native:fieldcalculator", {'INPUT':layer_A, 'FIELD_NAME':'distance', 'FIELD_TYPE':0, 'FIELD_LENGTH':0, 'FIELD_PRECISION':0, 'FORMULA': formular, 'OUTPUT':'TEMPORARY_OUTPUT'})['OUTPUT']


# clean-up
  • Hello, thanks for the suggested solution, I did everything as described but still get an empty “distance” column. Don’t not what I’m doing wrong.
    – Miron
    Commented Mar 14, 2022 at 14:12
  • I have updated my answer. It appears the layers must be present in the map canvas for the calculation to work.
    – Matt
    Commented Mar 21, 2022 at 14:21

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.