[GIS] How to flash selected feature using pyqgis

animationguipyqgisqgis

In ArcGIS, when one clicks a feature with the identify tool, it will flash/flicker, which makes the feature really easy to see for a moment. Reportedly, there is also a flash method in its ArcObject API.

Is there a way to flash a set of selected feature to the same effect with PyQGIS (2.x or 3.0)?

I searched around, and couldn't find any mention of this or examples

Best Answer

We can build a flashFeatures method in this way (give it a try in the QGIS Python Console):

from qgis.gui import QgsHighlight
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QColor

timer = QTimer( iface.mapCanvas() )
lstHighlights = []

def flashFeatures( featureIds ):
    global lstHighlights
    for f in iface.activeLayer().getFeatures( QgsFeatureRequest().setFilterFids(featureIds) ):
        h = QgsHighlight( iface.mapCanvas(), f.geometry(), iface.activeLayer() ) 
        h.setColor( QColor( 255,0,0,255 ) )
        h.setWidth( 5 )
        h.setFillColor( QColor( 255,0,0,100 ) )
        lstHighlights.append( h )
    timer.start( 500 ) # Milliseconds before finishing the flash

def finishFlash():
    timer.stop()
    global lstHighlights
    lstHighlights = []

timer.timeout.connect( finishFlash )

Call flashFeatures method passing it selected features Ids (activate first your layer in the Layers panel):

flashFeatures( iface.activeLayer().selectedFeaturesIds() )

If you want to flash features each time they are selected, you could use:

iface.activeLayer().selectionChanged.connect( flashFeatures )

enter image description here

Related Question