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?

Germán Carrillo
37.3k5 gold badges127 silver badges182 bronze badges
asked Mar 21, 2015 at 15:40

1 Answer 1

13

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)
answered Mar 21, 2015 at 18:04
2
  • 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. Commented Feb 13, 2019 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/…) Commented Feb 13, 2019 at 3:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.