[QGIS-Developer] Strange issue with custom QgsLayerTreeViewMenuProvider in python

Olivier Dalang olivier.dalang at gmail.com
Wed Mar 27 08:41:31 PDT 2019


Dear list,

I'm currently working on a plugin where I need to disable some actions from
the legend context menu (the one that appears when right-clicking).

I though of doing so by creating a custom QgsLayerTreeViewMenuProvider
class that would get the QMenu from the default menu provider, then do the
alterations, then return the altered QMenu.

I was almost able to get it working like this (stripped down example
below). This works the first time, when enabling the plugin in the plugin
manager. It also works from the Python console. But when the plugin is
loaded at the starting of QGIS, I get a hard crash upon right-clicking in
the legend.

Everything looks like either the layer tree view or the default menu
provider is not correctly initialized when the plugin's initGui is called.

I tried some workarounds, such as retrieving and replacing the provider a
bit later (using iface.projectRead or iface.currentLayerChanged signals),
which mitigates the issue, but I still get random crashes (around 1 out of
5-6 times).

Is there something I'm doing wrong ? Or can you think of another way to
achieve my goal ?

Thanks !!

Olivier

from qgis.PyQt.QtWidgets import QAction
from qgis.gui import QgsLayerTreeViewMenuProvider
from qgis.core import QgsMessageLog

class CustomMenuProvider(QgsLayerTreeViewMenuProvider):

def __init__(self, old_provider):
super().__init__()
self.old_provider = old_provider

def createContextMenu(self):
self.menu = self.old_provider.createContextMenu()
# make my modifications here
self.a = QAction('a', None)
self.menu.addAction(self.a)
return self.menu

class MyPlugin:

def __init__(self, iface):
self.iface = iface

def initGui(self):
self.old_provider = self.iface.layerTreeView().menuProvider()
self.my_provider = CustomMenuProvider(self.old_provider)
self.iface.layerTreeView().setMenuProvider(self.my_provider)
def unload(self):
pass
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20190327/94b066b4/attachment.html>


More information about the QGIS-Developer mailing list