[GIS] How to implement signals on add or modify feature

pythonqgisqt

I've created a test plug-in in QGIS successfully, but have had a hard time implementing a signal on a vector layer event (add or modify feature). I've add this to my initGUI method:

QObject.connect(self.iface.activeLayer(),SIGNAL("featureAdded(QgsFeatureId)"),self.addedGeometry)

and this definition:

def addedGeometry(self, intValue):
        QMessageBox.information( self.iface.mainWindow(),"Info", "Hi!!!" )

I get the following error when I load my plug-in:

QObject.connect(self.iface.activeLayer(),SIGNAL("featureAdded(QgsFeatureId)"),self.addedGeometry)
TypeError: arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): first argument of unbound method must have type 'QObject'

If anyone could help I would be very grateful! I can't find a lot of examples of implementing signals on QGIS objects.

Best Answer

self.iface.activeLayer() is relative to what layer is selected in the legend. If no layer is selected it returns 0 (not a QObject and resolved to 'NoneType'), which can not accept a signal/slot connection.

You'll need to do two things before building the signal/slot connection:

  1. Verify that self.iface.activeLayer() is in fact returning a QgsMapLayer and not 0
  2. Verify the active layer's LayerType is a QgsVectorLayer, which produces the featureAdded(QgsFeatureId) signal you're looking to connect to.

Edit: there is good information for writing plugins here:

Also, consider using new style PyQt connection syntax (here, once you have defined a variable 'vlayer' for the vector layer):

vlayer.featureAdded.connect(self.addedGeometry)

@pyqtSlot(int)
def addedGeometry(self, intValue):
    # fun stuff here
Related Question