[GIS] Creating Selection MapTool in PyQgis Custom Application

pyqgispythonqgis

I'm developing a custom GIS application using PyQgis API.

How can I let the user select features on the map using Maptools? I would like to replicate the select feature there in Qgis to make the selection on click of a button. My understanding is to use layer.selectedFeatures() function , but I am not sure of how to add the Selection Maptool to the mapcanvas and toolbar.

Best Answer

The selection map tools are not part of the qgis libs. You therefore have to reimplement the behavior if you are writing a custom app.

Maptool implementation

You will have to subclass qgis.gui.QgsMapTool and implement the canvasPressEvent, canvasMoveEvent and then modify the layer selection according to this.

You can have a look at the source files of the existing selection maptools ( e.g. qgsmaptoolselectpolygon.cpp ). They are C++ code, but pretty simple and should explain the concept.

Add to the mapcanvas

You will have to call the method setMapTool of your QgsMapCanvas instance and pass an instance of your own selection map tool as parameter.

myMapcanvas.setMapTool( mySelectionTool )

Toolbar

You have to create an action and connect its triggered signal to a method (slot) where you will set the map tool as outlined in the last paragraph.