3

I've been searching for a while to find a way to pass the layer that caused a signal to another function. I have a list of layers that that I want to apply automated attributes to. This has complicated this task a bit.
I've looked at some similar posts (1), but haven't been able to apply any solution to the code below.

  1. Send signal when attributes modified - QGIS 2.6

enter

from qgis.core import *
from qgis.utils import iface
from PyQt4.QtGui import  *

list_editable_layers = [layer1, layer2, layer3]

def openProject():  
    # list the layers to listen to for edits 
    editLayers  = list_editable_layers
    for l in editLayers:
        # Update feature attributes when new features are added or geometry changes
       l.featureAdded.connect(updateFeatureAttrs)
        l.attributeValueChanged.connect(updateFeatureAttrs)
        l.geometryChanged.connect(updateFeatureAttrs)


def updateFeatureAttrs( fId, geom=None ):
    # how do you pass the layer that cuased the signal to this function?
    editLayer   = iface.activeLayer()

def saveProject():
    pass

def closeProject():
    pass
1

I would make a class that stores the layer and connects the signal slots. Something like this:

Save this to My_Editable_Layer.py

class My_Editable_Layer():
    def __init__(self, layer):
        # Store the layer in the class field _mLayer
        self._mLayer = layer
        self.connectSignals()

    # A method that add/connect signals on this layer
    def connectSignals(self):
        self._mLayer.featureAdded.connect(self.uppdateFeatureAttrs)
        self._mLayer.attributeValueChanged.connect(self.uppdateFeatureAttrs)
        self._mLayer.geometryChanged.connect(self.uppdateFeatureAttrs)

    # This is the method that runs when the above connected signals is emitted
    def uppdateFeatureAttrs(self, fId, geom=None):
        # You have access to which layer by the class field
        print(f"{self._mLayer.sourceName()} edited")

And in your plugin(?) add

from My_Editable_Layer import My_Editable_Layer

list_editable_layers = [
    My_Editable_Layer(layer1),
    My_Editable_Layer(layer2),
    My_Editable_Layer(layer3)
]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.