16.3. Utilisation de la classe QgsPluginLayer

Si votre plugin utilise ses propres méthodes pour le rendu des couches, la meilleure façon de l’implémenter passe par l’écriture de vos propres types en vous basant sur la classe QgsPluginLayer

16.3.1. Héritage de la classe QgsPluginLayer

Vous trouverez ci dessous un exemple simple d’implémentation de la classe QgsPluginLayer, basé sur le code de l’extension Watermark

Le moteur de rendu personnalisé est la partie de l’implémentation qui définit le redu réel dans le canevas de carte.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class WatermarkLayerRenderer(QgsMapLayerRenderer):

    def __init__(self, layerId, rendererContext):
        super().__init__(layerId, rendererContext)

    def render(self):
        image = QImage("/usr/share/icons/hicolor/128x128/apps/qgis.png")
        painter = self.renderContext().painter()
        painter.save()
        painter.drawImage(10, 10, image)
        painter.restore()
        return True

class WatermarkPluginLayer(QgsPluginLayer):

    LAYER_TYPE="watermark"

    def __init__(self):
        super().__init__(WatermarkPluginLayer.LAYER_TYPE, "Watermark plugin layer")
        self.setValid(True)

    def createMapRenderer(self, rendererContext):
        return WatermarkLayerRenderer(self.id(), rendererContext)

    def setTransformContext(self, ct):
        pass

    # Methods for reading and writing specific information to the project file can
    # also be added:

    def readXml(self, node, context):
        pass

    def writeXml(self, node, doc, context):
        pass

Le plugin layer peux être ajouté a un projet et à la carte comme n’importe quelle autre couche :

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

Quand vous chargez un projet contenant ce type de couches, une classe constructeur est necessaire

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class WatermarkPluginLayerType(QgsPluginLayerType):

    def __init__(self):
        super().__init__(WatermarkPluginLayer.LAYER_TYPE)

    def createLayer(self):
        return WatermarkPluginLayer()

    # You can also add GUI code for displaying custom information
    # in the layer properties
    def showLayerProperties(self, layer):
        pass


# Keep a reference to the instance in Python so it won't
# be garbage collected
plt =  WatermarkPluginLayerType()

assert QgsApplication.pluginLayerRegistry().addPluginLayerType(plt)