I was able to get it working with the code below:
layer1 = QgsVectorLayer("Point?crs=EPSG:4326", "my layer", "memory")
QgsProject.instance().addMapLayer(layer1, False)
root = QgsProject.instance().layerTreeRoot()
node = root.addLayer(layer1)
indicator = QgsLayerTreeViewIndicator(iface.layerTreeView())
indicator.setToolTip('Test')
indicator.setIcon(QIcon(':/images/themes/default/mActionIdentify.svg'))
indicator.clicked.connect(lambda: print('indicator clicked'))
view = iface.layerTreeView()
view.addIndicator(node, indicator)
def rows_inserted(parent, first, last):
nodes = root.findLayers()
for n in nodes:
if n.layer().id() == layer1.id():
if not view.indicators(n):
view.addIndicator(n, indicator)
conn = view.layerTreeModel().rowsInserted.connect(rows_inserted)
After removing layer, clean up by disconnecting signal/slot and deleting indicator object:
QObject.disconnect(conn)
del indicator
Screencast shows this working:
Based very loosely on source code in qgslayertreeviewindicatorprovider.cpp which would probably take care of this nicely but does not seem to be exposed in the Python API bindings.