Friday 1 March 2019

python 2.7 - Setting different context menu actions for each layer type with PyQGIS


I want to set different actions(context menu) for vectors,rasters,etc .


class MyMenuProvider(QgsLayerTreeViewMenuProvider):
def __init__(self, view):
QgsLayerTreeViewMenuProvider.__init__(self)
self.view = view

def createContextMenu(self):
if not self.view.currentLayer():
return None

m = QMenu()
m.addAction("Show Attribute Table", self.openAttributeTable)
return m

def openAttributeTable(self):
#iface1.openFeatureForm(iface1.activeLayer(), feature, False)
iface1.showAttributeTable(iface1.activeLayer())

then using it as


 view = iface1.layerTreeView()

provider = MyMenuProvider(view)
view.setMenuProvider(provider)

But this sets menu provider for all layers , I want to have different actions for different layers



Answer



You can always have a look at how QGIS does it to get an idea.


In your case, you can use a conditional expression to evaluate the layer type. If current layer is a vector you add certain actions, if not, you add others.


This is a basic example (see the createContextMenu function):


from qgis.core import QgsVectorLayer, QgsRasterLayer
from qgis.gui import QgsLayerTreeViewMenuProvider

from PyQt4.QtGui import QMenu

class MyMenuProvider(QgsLayerTreeViewMenuProvider):

def __init__(self, view):
QgsLayerTreeViewMenuProvider.__init__(self)
self.view = view
self.defaultActions = view.defaultActions()

def createContextMenu(self):

if not self.view.currentLayer():
return None
m = QMenu()
m.addAction("Open layer properties", self.openLayerProperties)
m.addSeparator()

if type(self.view.currentLayer()) == QgsVectorLayer:
m.addAction("Show Feature Count", self.featureCount)
m.addAction("Another vector-specific action", self.vectorAction)
elif type(self.view.currentLayer()) == QgsRasterLayer:

m.addAction("Zoom 100%", self.zoom100)
m.addAction("Another raster-specific action", self.rasterAction)

return m

def openLayerProperties(self):
iface.showLayerProperties(self.view.currentLayer())

def featureCount(self):
self.defaultActions.actionShowFeatureCount().trigger()


def vectorAction(self):
pass

def zoom100(self):
iface.actionZoomActualSize().trigger()

def rasterAction(self):
pass


view = iface.layerTreeView()
provider = MyMenuProvider(view)
view.setMenuProvider(provider)

Which produces:


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...