QGIS Plugins – Sending Signal When Attributes Modified in QGIS 2.6

pluginspyqgispythonqgis

For a QGIS 2.6 python plugin, I am trying to send a signal when an attribute value is changed (values for an existing feature are updated or added and the attribute form dialog is accepted). This signal should then connect to another function. Note, that the feature is not being added (it already existed, and attributes are being modified after identifying a feature while in edit mode). This is why the featureAdded signal doesn't work.

So far, i've tried using attributeValueChanged, editCommandEnded and layerModified signals from the vector layer class in this way with no success.

def myFunction(self):
    self.myLayer.attributeValueChanged.connect(self.myOtherFunction)

def myOtherFunction(self):
    self.myLayer.dostuff
    self.dlg.show()

Best Answer

I've tested the attributeValueChanged SIGNAL in a created-from-scratch test plugin using QGIS v.2.6.1

You can connect the SIGNAL to your slot this way (I did it in my run() method):

def run(self):
    self.lyr = self.iface.mapCanvas().layers()[0]
    self.lyr.attributeValueChanged.connect(self.mySlot)

And then, you have two options to write your slot (see mySlot and mySlot2):

def mySlot(self):
    QMessageBox.information( self.iface.mainWindow(), "Test", 
        "Attributes were changed!!!", QMessageBox.Ok )

def mySlot2(self, fid, idx, v):
    QMessageBox.information( self.iface.mainWindow(), "Test", 
        "Attributes changed for feature " + str(fid), QMessageBox.Ok )

Both slots work, just replace self.mySlot by self.mySlot2 in the connect method above if you want to switch between them.

If you want to get the test plugin, run it on your QGIS, and have a look at the code, you can access to it here. You find installation and usage instructions in the README file.