QGIS 3.6.2 - Noosa
This will generate a memory layer of a spatial join between the polygon layer being edited and an existing points layer. The fields to be joined can be specified with the JOIN_FIELDS
option.
The function is fired when editing a shape is finished (right-click during editing). It saves the edits made (commitChanges()
) and then performs the join by location.
pnts = QgsProject.instance().mapLayersByName('points')[0]
poly = QgsProject.instance().mapLayersByName('polygons')[0]
def join_on_edit():
# save edits made to the polygon layer
poly.commitChanges()
# remove any layers called 'joined_attributes' (prevents outputs stacking up)
for lyr in QgsProject.instance().mapLayers().values():
if lyr.name() == 'joined_attributes':
QgsProject.instance().removeMapLayer(lyr)
# proceed only if the layer being edited has any features (prevents an empty results layer being created if all features from poly layer are deleted)
if len(list(poly.getFeatures())) > 0:
# join by location using an intersect predicate
l = processing.run("qgis:joinattributesbylocation", {'INPUT':poly,'JOIN':pnts,'PREDICATE':[0],'JOIN_FIELDS':[],'METHOD':0,'DISCARD_NONMATCHING':False,'PREFIX':'','OUTPUT':'memory:joined_attributes'})
# add the memory layer result
QgsProject.instance().addMapLayer(l['OUTPUT'])
# active layer switches to newly created join by location layer so this reverts focus to editing layer
iface.setActiveLayer(poly)
# re-open the edit session
poly.startEditing()
# 'click' the add feature button in the digitizing toolbar for continuation of editing
for a in iface.mainWindow().children():
if a.objectName() == 'mActionAddFeature':
a.trigger()
break
# connect the layerModified signal with the function
poly.layerModified.connect(join_on_edit)