I would like to override the default contextual menu in QGIS 3 in the ToC.

I've created a class that inherit from QgsLayerTreeViewMenuProvider.

from qgis.gui import QgsLayerTreeViewMenuProvider
from qgis.PyQt.QtWidgets import QMenu

class LayerTreeViewMenuProvider(QgsLayerTreeViewMenuProvider):

    def __init__(self):

    def createContextMenu(self):
        menu = QMenu()
        menu.addAction('Test', lambda : print('test'))
        return menu

This code works well but I would like to get in all cases (right click in ToC or to a vector layer, raster layer, ...) the default contextual menu to adapt it. So I've made :

def createContextMenu(self):
    menu = super().createContextMenu()
    return menu

That doesn't work, I've got a RecursionError: maximum recursion depth exceeded

  • Have you already seen this answer? Dec 23 '20 at 14:27
  • @GermánCarrillo I've already seen this answer but it doesn't make what i want.I would like to modify the menu. With this solution, i must to rewrite all the code of this method QgsAppLayerTreeViewMenuProvider::createContextMenu() in python. I only want to override this menu created to add an entry in all cases
    – TrsBar
    Jan 4 '21 at 7:54
  • 1
    You cannot modify the menu, since the menu has to be built each time it is called. Nonetheless, you can use the default actions of the layer tree, like in this example: gis.stackexchange.com/questions/267613/… Jan 5 '21 at 3:04
  • @GermánCarrillo Thanks for your answer. If I use the super () method in my class. Should I be able to retrieve the QMenu object? In this case, I could overload it for my needs ?
    – TrsBar
    Jan 5 '21 at 8:13
  • 1
    No, you can't, because the menu object is built in the createContextMenu() method, and that is exactly what you need to overwrite to add your own action (see the 'More about the view' section here). Additionally, you can see how QGIS devs do it here. Jan 5 '21 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.