[GIS] Dynamically selecting t layer features implementing canvasMoveEvent of QgsMapToolIdentify class

featureslayerspyqgis

In my QGIS plugin I need to dynamically select features of a layer with the mouse move event.

In Programatically check for mouse click in PyQGIS? the canvasMoveEvent of the QgsMapTool class is implemented to get x,y coordinates, in Getting attribute value from vector layer after mouse click in PyQGIS? no "move event" is explored (but I think it's not important thing) but they recommended QgsMapToolIdentify to retrieve information about features/layer.

I tried both of these 2 strategies but neither works fine.

Here is my code:

In the dialog implemetation (in the method connected to a button clicked):

    selectTool = CustomSelectTool(self.iface.mapCanvas(), self)
    self.iface.mapCanvas().setMapTool(selectTool)

1) QgsMapTool

class CustomSelectTool(QgsMapTool):   

    def __init__(self, canvas):
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas
        self.identifier = QgsMapToolIdentify(canvas)
        self.featureId = None

    def canvasMoveEvent(self, ev):
        ### IT WORKS BUT MOUSE TRACKING IS NOT VERY ACCURATE
        indentifiedFeatures = self.identifier.identify(ev.x(), ev.y(), self.identifier.TopDownAll)
        if not indentifiedFeatures[0].mFeature.id() == self.featureId: 
            self.featureId = indentifiedFeatures[0].mFeature.id()
            indentifiedFeatures[0].mLayer.select(self.featureId)

the cursor doesn't seem to be very reactive, sometimes it misses some feature.

2) QgsMapToolIdentify

    class CustomSelectTool(QgsMapToolIdentify):   

        def __init__(self, canvas):
            QgsMapToolIdentify.__init__(self, canvas)
            self.canvas = canvas
            self.featureId = None

        def canvasMoveEvent(self, ev):
            ### NOTHING HAPPEN (IT SEEMS TO BE NEVER CALLED)
            indentifiedFeatures = self.identify(ev.x(), ev.y(), self.identifier.TopDownAll)
            if not indentifiedFeatures[0].mFeature.id() == self.featureId: 
                self.featureId = indentifiedFeatures[0].mFeature.id()
                indentifiedFeatures[0].mLayer.select(self.featureId)

in this case nothing happen when I move my mouse on layers in the map. If I put a "print" in the canvasMoveEvent method it doesn't print.

In Capturing mouse movement on QgsMapCanvas? they said there are another two ways to follow:

3) xyCoordinates event

4) eventFilter

but I'm not so expert in PyQGIS developing and no simple examples are shown.

How do I solve this problem?

Best Answer

Solved!

with QgsMapToolIdentify tool enabling mouse tracking is needed.

I put this in the method of connected to the button

      self.setMouseTracking(True) 

before

      selectTool = CustomSelectTool(self.iface.mapCanvas(), self)

It works fine!