PyQGIS – Select Features by Mouse Click Not Working

pyqgis-3qgis-3qgis-plugins

I'm using the solution provided in this question. but when I click on the canvas nothing happens. here is my code

from qgis.gui import QgsMapToolIdentifyFeature, QgsMapToolIdentify
from qgis.core import (
    Qgis, QgsVectorLayer
)

class selectTool(QgsMapToolIdentifyFeature):

        def __init__(self, iface, layer):
            self.iface = iface
            self.canvas = self.iface.mapCanvas()
            self.layer = layer
            QgsMapToolIdentifyFeature.__init__(self, self.canvas, self.layer)
            self.iface.currentLayerChanged.connect(self.active_changed)
            
        def active_changed(self, layer):
            self.layer.removeSelection()
            if isinstance(layer, QgsVectorLayer) and layer.isSpatial():
                self.layer = layer
                self.setLayer(self.layer)
                
        def canvasPressEvent(self, event):
            found_features = self.identify(event.x(), event.y(), [self.layer], QgsMapToolIdentify.TopDownAll)
            print(found_features)
            self.layer.selectByIds([f.mFeature.id() for f in found_features], QgsVectorLayer.AddToSelection)
            
        def deactivate(self):
            self.layer.removeSelection()

And here is the code that instantiates this class, it is a function that is called when I push a button on my plugin, I have confirmed that the button push is tied to this function by using this print statement. after the button is pushed I can click in the canvas on features but no feature is selected, I have also confirmed that the correct layer is selected.

    def start_line_edit(self):
        print("button pushed")
        t = selectTool(iface, self.poly_layer)
        iface.mapCanvas().setMapTool(t)

Best Answer

For me, the instance of selectTool is deleted at the end of the start_line_edit function.

So try :

def start_line_edit(self):
    print("button pushed")
    self.t = selectTool(iface, self.poly_layer)
    iface.mapCanvas().setMapTool(self.t)
Related Question