重要

翻訳は あなたが参加できる コミュニティの取り組みです。このページは現在 100.00% 翻訳されています。

18. プラグインレイヤを使う

ヒント

pyqgisコンソールを使わない場合、このページにあるコードスニペットは次のインポートが必要です:

1from qgis.core import (
2    QgsPluginLayer,
3    QgsPluginLayerType,
4    QgsMapLayerRenderer,
5    QgsApplication,
6    QgsProject,
7)
8
9from qgis.PyQt.QtGui import QImage

もしプラグインがマップレイヤをレンダリングするために独自のメソッドを使うのであれば、 QgsPluginLayer に基づいて独自のレイヤタイプを書くのが実装するための最良の方法かもしれません。

18.1. QgsPluginLayerのサブクラス化

以下は最小限のQgsPluginLayerの実装例です。これは Watermark example plugin のオリジナルのコードを基にしています。

カスタムレンダラーは、キャンバスへの実際の描画を定義する実装の一部です。

 1class WatermarkLayerRenderer(QgsMapLayerRenderer):
 2
 3    def __init__(self, layerId, rendererContext):
 4        super().__init__(layerId, rendererContext)
 5
 6    def render(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
14class WatermarkPluginLayer(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    def createMapRenderer(self, rendererContext):
23        return WatermarkLayerRenderer(self.id(), rendererContext)
24
25    def setTransformContext(self, ct):
26        pass
27
28    # Methods for reading and writing specific information to the project file can
29    # also be added:
30
31    def readXml(self, node, context):
32        pass
33
34    def writeXml(self, node, doc, context):
35        pass

プラグインレイヤは、他のマップレイヤと同じようにプロジェクトやキャンバスに追加することができます:

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

このようなレイヤを含むプロジェクトをロードする場合、ファクトリークラスが必要です:

 1class WatermarkPluginLayerType(QgsPluginLayerType):
 2
 3    def __init__(self):
 4        super().__init__(WatermarkPluginLayer.LAYER_TYPE)
 5
 6    def createLayer(self):
 7        return WatermarkPluginLayer()
 8
 9    # You can also add GUI code for displaying custom information
10    # in the layer properties
11    def showLayerProperties(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)