0

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)

1 Answer 1

3

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)
1
  • Oh wow, perfect. Thank you!
    – tbob
    May 31, 2022 at 17:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.