Monday, 3 August 2015

pyqgis - How to define an event for features selected in mapcanvas in qgis using python


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?



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...