How to flash selected feature using pyqgis?

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


In 3.0 you can use QGIS's built in flashFeatureIds method on MapCanvas objects

canvas = iface.mapCanvas()
layer = iface.activeLayer()
my_features_ids = [42, 43, 45]
canvas.flashFeatureIds(layer, my_features_ids)

This method also lets you modify the style of the flashing