4

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?

10

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)
  • Germán, if I'm changing a layer's selection in a plugin, where would I put the code that you indicate in your answer? It does work fine in the Python console, but I want it to be invoked within my Python plugin... or wherever it should be placed. – Rudy Stricklan Feb 13 at 0:27
  • This really depends on your use case. You can have the slot (i.e., myFunction above) and in the function you create or get your layer define the SIGNAL-SLOT connection. As simply as that. However, be careful with setting the connection several times (e.g., each time you call a dialog in your plugin, see gis.stackexchange.com/questions/137160/…) – Germán Carrillo Feb 13 at 3:36

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.