By combining information from these posts:
How to create and remove multiple QgsRubberBands in PyQGIS?
I produced following code for getting feature attributes and creating and removing its respectives QgsRubberBands after clicking on Map Canvas where features exist for a polygon vector layer.
from qgis.gui import QgsRubberBand, QgsMapToolIdentifyFeature
from PyQt5.QtGui import QColor
def onFeatureIdentified(feature):
fid = feature.id()
rbList.append( [feature.id(), QgsRubberBand(iface.mapCanvas(), True)])
print ("feature selected : " + str(fid))
for i, item in enumerate(feature.attributes()):
print (feature.fields().names()[i] + ": " + str(item))
if len(rbList) == 2:
iface.mapCanvas().scene().removeItem(rbList[0][1])
del rbList[0]
rbList[0][1].setColor( QColor( 'red' ) )
rbList[0][1].setWidth( 5 )
rbList[0][1].addGeometry(feature.geometry(), None)
rbList = [] # To store the created rbs and feature ids
layer = iface.activeLayer()
mc=iface.mapCanvas()
mapTool = QgsMapToolIdentifyFeature(mc)
mapTool.setLayer(layer)
mc.setMapTool(mapTool)
mapTool.featureIdentified.connect(onFeatureIdentified)
After running above code, it can be observed that it works as expected (see following images):
however, I cannot find out any useful method (at pyqgis script) for removing last created QgsRubberBand by clicking in Map Canvas area where doesn't exist any feature. It could be manually done by using following instruction at Python Console:
iface.mapCanvas().scene().removeItem(rbList[0][1])
My question is how can I implement former instruction in the previous code to get expected result.