18. Using Plugin Layers

Hint

The code snippets on this page need the following imports if you’re outside the pyqgis console:

1fromqgis.coreimport (
2 QgsPluginLayer,
3 QgsPluginLayerType,
4 QgsMapLayerRenderer,
5 QgsApplication,
6 QgsProject,
7)
8
9fromqgis.PyQt.QtGuiimport QImage

If your plugin uses its own methods to render a map layer, writing your own layer type based on QgsPluginLayer might be the best way to implement that.

18.1. Subclassing QgsPluginLayer

Below is an example of a minimal QgsPluginLayer implementation. It is based on the original code of the Watermark example plugin.

The custom renderer is the part of the implement that defines the actual drawing on the canvas.

 1classWatermarkLayerRenderer(QgsMapLayerRenderer):
 2
 3 def__init__(self, layerId, rendererContext):
 4 super().__init__(layerId, rendererContext)
 5
 6 defrender(self):
 7 image = QImage("/usr/share/icons/hicolor/128x128/apps/qgis.png")
 8 painter = self.renderContext().painter()
 9 painter.save()
10 painter.drawImage(10, 10, image)
11 painter.restore()
12 return True
13
14classWatermarkPluginLayer(QgsPluginLayer):
15
16 LAYER_TYPE="watermark"
17
18 def__init__(self):
19 super().__init__(WatermarkPluginLayer.LAYER_TYPE, "Watermark plugin layer")
20 self.setValid(True)
21
22 defcreateMapRenderer(self, rendererContext):
23 return WatermarkLayerRenderer(self.id(), rendererContext)
24
25 defsetTransformContext(self, ct):
26 pass
27
28 # Methods for reading and writing specific information to the project file can
29 # also be added:
30
31 defreadXml(self, node, context):
32 pass
33
34 defwriteXml(self, node, doc, context):
35 pass

The plugin layer can be added to the project and to the canvas as any other map layer:

plugin_layer = WatermarkPluginLayer()
QgsProject.instance().addMapLayer(plugin_layer)

When loading a project containing such a layer, a factory class is needed:

 1classWatermarkPluginLayerType(QgsPluginLayerType):
 2
 3 def__init__(self):
 4 super().__init__(WatermarkPluginLayer.LAYER_TYPE)
 5
 6 defcreateLayer(self):
 7 return WatermarkPluginLayer()
 8
 9 # You can also add GUI code for displaying custom information
10 # in the layer properties
11 defshowLayerProperties(self, layer):
12 pass
13
14
15# Keep a reference to the instance in Python so it won't
16# be garbage collected
17plt = WatermarkPluginLayerType()
18
19assert QgsApplication.pluginLayerRegistry().addPluginLayerType(plt)