Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am implementing a python based plugin for use with QGIS 1.8.

Most of it's user interface is contained within a QDockWidget but there are some layer specific controls I would like to append to the context menu displayed when the user right-clicks on the Table Of Contents.

Is there a way for me to manipulate this menu?

share|improve this question
up vote 2 down vote accepted

Applies to the current development version or the upcoming release 2.0.

You can use QgsLegendInterface.addLegendLayerAction for this purpose. This method lets you add new menu entries for a LayerType (VectorLayer, RasterLayer, PluginLayer)

a = QAction( u"My Action", iface.legendInterface() )
iface.legendInterface().addLegendLayerAction( a, u"My Plugin Menu", u"id1", QgsMapLayer.VectorLayer, True )

If you set the allLayers parameter of addLegendLayerAction to False you can add the action only for specific layers. Given a variable myLayer pointing to a QgsMapLayer:

aLyr = QAction( u"My Layer Action", iface.legendInterface() )
iface.legendInterface().addLegendLayerAction( aLyr, u"My Plugin Menu", u"id2", QgsMapLayer.VectorLayer, False )
iface.legendInterface().addLegendLayerActionForLayer( aLyr, myLayer )

You would then normally connect the QAction.triggered signal to a slot with the code you want to execute when your menu entry is clicked.

You should remove the action by calling the appropriate removeLegendLayerAction when your plugin is exiting.

iface.legendInterface().removeLegendLayerAction( a )
iface.legendInterface().removeLegendLayerAction( aLyr )
share|improve this answer
Thanks, nice update. – Kelly Thomas Apr 26 '13 at 6:09

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.