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:
length(
shortest_line(
$geometry,
geometry(get_feature('layer_B','fieldname',attribute('fieldname')))
)
)
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?
Best Answer
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: