[GIS] How to define an event for features selected in mapcanvas in qgis using python

pyqgisqgisqgis-plugins

I have created a push button, when it is clicked it calls the function 'selectfeatures'. This function will call the Select feature by free hand tool of QGIS and allows the user to select features in the mapcanvas. What I need is my event to recognize the features selected in mapcanvas and call another function. How should this be accomplished?

Best Answer

If I got you right, you can use the SIGNAL selectionChanged from your vector layer and connect it to your other function (which must accept an argument to receive selected features' ids).

For example, load a vector layer to QGIS, activate it in the ToC and run the following code in the QGIS Python console. You should see the function is running after a new selection, recognizing the selected features' ids.

lyr=iface.activeLayer()
def myFunction(selFeatures):
    print str(len(selFeatures)) + " features were selected: " + str(selFeatures)

lyr.selectionChanged.connect(myFunction)
Related Question