Python プラグインの開発

Pythonプログラミング言語でプラグインを作成することが可能です。C++で書かれた古典的なプラグインと比較して、これらはPython言語の動的な性質により、記述や理解、維持、配布が簡単です。

Python plugins are listed together with C++ plugins in QGIS plugin manager. They are searched for in these paths:

  • UNIX/Mac: ~/.qgis/python/plugins および (qgis_prefix)/share/qgis/python/plugins

  • Windows: ~/.qgis/python/plugins および (qgis_prefix)/python/plugins

Home directory (denoted by above ~) on Windows is usually something like C:\Documents and Settings\(user) (on Windows XP or earlier) or C:\Users\(user). Since Quantum GIS is using Python 2.7, subdirectories of these paths have to contain an __init__.py file to be considered Python packages that can be imported as plugins.

ステップ:

  1. アイデア: 新しいQGISプラグインでやりたいことのアイデアを持ちます。なぜそれを行うのですか? どのような問題を解決しますか? その問題のための別のプラグインは既にありますか?

  2. Create files: Create the files described next. A starting point (__init__.py). Fill in the プラグインメタデータ (metadata.txt) A main python plugin body (mainplugin.py). A form in QT-Designer (form.ui), with its resources.qrc.
  3. コードを書く: mainplugin.py 内にコードを記述する

  4. テスト: QGISを閉じて再度開き、あなたのプラグインをインポートします。すべてがOKかチェックして下さい。

  5. Publish: Publish your plugin in QGIS repository or make your own repository as an “arsenal” of personal “GIS weapons”.

プラグインを書く

Since the introduction of Python plugins in QGIS, a number of plugins have appeared - on Plugin Repositories wiki page you can find some of them, you can use their source to learn more about programming with PyQGIS or find out whether you are not duplicating development effort. The QGIS team also maintains an 公式のpythonプラグインリポジトリ. Ready to create a plugin but no idea what to do? Python Plugin Ideas wiki page lists wishes from the community!

プラグインファイル

Here’s the directory structure of our example plugin

PYTHON_PLUGINS_PATH/
  MyPlugin/
    __init__.py    --> *required*
    mainPlugin.py  --> *required*
    metadata.txt   --> *required*
    resources.qrc  --> *likely useful*
    resources.py   --> *compiled version, likely useful*
    form.ui        --> *likely useful*
    form.py        --> *compiled version, likely useful*

ファイルが意味すること:

  • __init__.py = The starting point of the plugin. It has to have the classFactory() method and may have any other initialisation code.
  • mainPlugin.py = プラグインの主なワーキングコード。このプラグインの動作に関するすべての情報と主要なコードを含みます。

  • resources.qrc = The .xml document created by Qt Designer. Contains relative paths to resources of the forms.
  • resources.py = 上記の.qrcファイルがPythonに変換されたもの。

  • form.ui = The GUI created by Qt Designer.
  • form.py = 上記のform.uiがPythonに変換されたもの。

  • metadata.txt = QGIS >= 1.8.0 で必要です。全般情報やバージョン、名前、そしてプラグインのウェブサイトやインフラストラクチャによって使用されるいくつかのメタデータが含まれます。QGIS 2.0 以降では __init__.py からのメタデータは受け付けられず、 metadata.txt が必要です。

ここ では典型的なQGISのPythonプラグインの基本的なファイル(スケルトン)をオンラインで自動的に作成することができます。

また、 Plugin Builder と呼ばれるQGISプラグインがあります。QGISからプラグインテンプレートを作成しますがインターネット接続を必要としません。2.0に互換性のあるソースを生成しますので推奨される選択肢です。

警告

If you plan to upload the plugin to the 公式のpythonプラグインリポジトリ you must check that your plugin follows some additional rules, required for plugin 検証

プラグインの内容

上述のファイル構造の中のそれぞれのファイルに何を追加するべきかについての情報および例を示します。

プラグインメタデータ

まず、プラグインマネージャーは名前や説明などプラグインに関する基本的な情報を取得する必要があります。 metadata.txt ファイルはこの情報を記載するのに適切な場所です。

重要

全てのメタデータはUTF-8のエンコーディングでなければいけません。

メタデータ名

必須

注意

name True

プラグインの名前を含んでいる短い文字列

qgisMinimumVersion True

QGISの最小バージョンのドット付き表記

qgisMaximumVersion False

QGISの最大バージョンのドット付き表記

description True

プラグインを説明する短いテキスト。HTMLは使用できません。

about False

プラグインを詳細に説明するより長いテキスト。HTMLは使用できません。

version True

バージョンのドット付き表記の短い文字列

author True

作者名

email True

作者の電子メールアドレス。Webサイトには 表示されません

changelog False

文字列。複数行でもよいですがHTMLは使用できません。

experimental False

ブール型のフラグ。 True または False

deprecated False

ブール型のフラグ。 True または False. アップロードされたバージョンだけではなくプラグイン全体に適用されます。

tags False comma separated list, spaces are allowed inside individual tags
homepage False

プラグインのホームページを指す有効なURL

repository False

ソースコードリポジトリの有効なURL

tracker False

チケットとバグ報告のための有効なURL

icon False

ファイル名または相対パス (プラグインの圧縮されたパッケージのベースフォルダに対する)

category False

Raster, Vector, Database, Web のいずれか

By default, plugins are placed in the Plugins menu (we will see in the next section how to add a menu entry for your plugin) but they can also be placed the into Raster, Vector, Database and Web menus.

A corresponding “category” metadata entry exists to specify that, so the plugin can be classified accordingly. This metadata entry is used as tip for users and tells them where (in which menu) the plugin can be found. Allowed values for “category” are: Vector, Raster, Database or Web. For example, if your plugin will be available from Raster menu, add this to metadata.txt

category=Raster

ノート

qgisMaximumVersion が空の場合、 公式のpythonプラグインリポジトリ にアップロードされた時にメジャーバージョン + .99 に自動的に設定されます。

An example for this metadata.txt

; the next section is mandatory

[general]
name=HelloWorld
[email protected]
author=Just Me
qgisMinimumVersion=2.0
description=This is an example plugin for greeting the world.
    Multiline is allowed:
    lines starting with spaces belong to the same
    field, in this case to the "description" field.
    HTML formatting is not allowed.
about=This paragraph can contain a detailed description
    of the plugin. Multiline is allowed, HTML is not.
version=version 1.2
; end of mandatory metadata

; start of optional metadata
category=Raster
changelog=The changelog lists the plugin versions
    and their changes as in the example below:
    1.0 - First stable release
    0.9 - All features implemented
    0.8 - First testing release

; Tags are in comma separated value format, spaces are allowed within the
; tag name.
; Tags should be in English language. Please also check for existing tags and
; synonyms before creating a new one.
tags=wkt,raster,hello world

; these metadata can be empty, they will eventually become mandatory.
homepage=http://www.itopen.it
tracker=http://bugs.itopen.it
repository=http://www.itopen.it/repo
icon=icon.png

; experimental flag (applies to the single version)
experimental=True

; deprecated flag (applies to the whole plugin and not only to the uploaded version)
deprecated=False

; if empty, it will be automatically set to major version + .99
qgisMaximumVersion=2.0

__init__.py

This file is required by Python’s import system. Also, Quantum GIS requires that this file contains a classFactory() function, which is called when the plugin gets loaded to QGIS. It receives reference to instance of QgisInterface and must return instance of your plugin’s class from the mainplugin.py — in our case it’s called TestPlugin (see below). This is how __init__.py should look like

def classFactory(iface):
  from mainPlugin import TestPlugin
  return TestPlugin(iface)

## any other initialisation needed

mainPlugin.py

This is where the magic happens and this is how magic looks like: (e.g. mainPlugin.py)

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *

# initialize Qt resources from file resources.py
import resources

class TestPlugin:

  def __init__(self, iface):
    # save reference to the QGIS interface
    self.iface = iface

  def initGui(self):
    # create action that will start plugin configuration
    self.action = QAction(QIcon(":/plugins/testplug/icon.png"), "Test plugin", self.iface.mainWindow())
    self.action.setObjectName("testAction")
    self.action.setWhatsThis("Configuration for test plugin")
    self.action.setStatusTip("This is status tip")
    QObject.connect(self.action, SIGNAL("triggered()"), self.run)

    # add toolbar button and menu item
    self.iface.addToolBarIcon(self.action)
    self.iface.addPluginToMenu("&Test plugins", self.action)

    # connect to signal renderComplete which is emitted when canvas
    # rendering is done
    QObject.connect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter *)"), self.renderTest)

  def unload(self):
    # remove the plugin menu item and icon
    self.iface.removePluginMenu("&Test plugins",self.action)
    self.iface.removeToolBarIcon(self.action)

    # disconnect form signal of the canvas
    QObject.disconnect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter *)"), self.renderTest)

  def run(self):
    # create and show a configuration dialog or something similar
    print "TestPlugin: run called!"

  def renderTest(self, painter):
    # use painter for drawing to map canvas
    print "TestPlugin: renderTest called!"

The only plugin functions that must exist in the main plugin source file (e.g. mainPlugin.py) are:

  • __init__ –> which gives access to Quantum GIS’ interface
  • initGui() –> called when the plugin is loaded
  • unload() –> called when the plugin is unloaded

You can see that in the above example, the addPluginToMenu() is used. This will add the corresponding menu action to the Plugins menu. Alternative methods exist to add the action to a different menu. Here is a list of those methods:

  • addPluginToRasterMenu()
  • addPluginToVectorMenu()
  • addPluginToDatabaseMenu()
  • addPluginToWebMenu()

それらはすべて addPluginToMenu() メソッドと同じ構文です。

プラグインエントリの編成の一貫性を保つために、これらの定義済みのメソッドのいずれかでプラグインメニューを追加することが推奨されます。ただし、次の例に示すようにメニューバーに直接カスタムメニューグループを追加することができます:

def initGui(self):
    self.menu = QMenu(self.iface.mainWindow())
    self.menu.setObjectName("testMenu")
    self.menu.setTitle("MyMenu")

    self.action = QAction(QIcon(":/plugins/testplug/icon.png"), "Test plugin", self.iface.mainWindow())
    self.action.setObjectName("testAction")
    self.action.setWhatsThis("Configuration for test plugin")
    self.action.setStatusTip("This is status tip")
    QObject.connect(self.action, SIGNAL("triggered()"), self.run)
    self.menu.addAction(self.action)

    menuBar = self.iface.mainWindow().menuBar()
    menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu)

def unload(self):
    self.menu.deleteLater()

カスタマイズを可能にするためにQActionとQMenuのobjectNameをプラグイン固有の名前に設定することを忘れないで下さい。

リソースファイル

You can see that in initGui() we’ve used an icon from the resource file (called resources.qrc in our case)

<RCC>
  <qresource prefix="/plugins/testplug" >
     <file>icon.png</file>
  </qresource>
</RCC>

It is good to use a prefix that will not collide with other plugins or any parts of QGIS, otherwise you might get resources you did not want. Now you just need to generate a Python file that will contain the resources. It’s done with pyrcc4 command

pyrcc4 -o resources.py resources.qrc

And that’s all... nothing complicated :)

If you’ve done everything correctly you should be able to find and load your plugin in the plugin manager and see a message in console when toolbar icon or appropriate menu item is selected.

本物のプラグインに取り組んでいる時は別の(作業)ディレクトリでプラグインを書いて、UIとリソースファイルを生成してプラグインをQGISにインストールするmakefileを作成するのが賢明です。

ドキュメント

プラグインのドキュメントはHTMLヘルプファイルとして記述できます。 qgis.utils モジュールは他のQGISのヘルプと同じ方法でヘルプファイルブラウザを開く showPluginHelp() 関数を提供しています。

showPluginHelp() 関数は呼び出し元のモジュールと同じディレクトリでヘルプファイルを探します。 index-ll_cc.html, index-ll.html, index-en.html, index-en_us.html, index.html の順に探し、はじめに見つけたものを表示します。ここで ll_cc はQGISのロケールです。ドキュメントの複数の翻訳をプラグインに含めることができます。

showPluginHelp() 関数は引数をとることができます。packageName引数はヘルプが表示されるプラグインを識別します。filename引数は検索しているファイル名の”index”を置き換えます。そしてsection引数はブラウザが表示位置を合わせるドキュメント内のHTMLアンカータグの名前です。