Python プラグインを構成する¶
プラグインを作成するには、以下の手順に従います。
アイデア:新しいQGISプラグインで何をしたいか考えます。なぜそれを行うのですか? どのような問題を解決したいですか? その問題に対して別のプラグインは既にありますか?
ファイルの作成:最低限必要になるのは、起点となる
__init__.py
; と、プラグインメタデータ を記載するmetadata.txt
です。 それからご自身の設計を実装するファイルとして、メインのPythonプラグイン本体のためにたとえばmainplugin.py
ファイルを。また外観のためのQT Designerのフォームform.ui
とそのリソースファイルresources.qrc
もおそらく必要になります。コードを書く:
mainplugin.py
内にコードを記述します。テスト:QGISをいったん閉じてから再度起動し、作成したプラグインをもう一度読み込みます。すべてがうまくいくかどうか確認してください。
公開:出来上がったプラグインをQGISリポジトリに公開するか、ご自身のリポジトリをパーソナルな「GIS兵器」の兵器庫として作りましょう。
プラグインを書く¶
QGISにPythonプラグインが導入されて以来、数多くのプラグインが登場しました。 QGISチームは Official Python plugin repository を保守しています。それらのソースを使用して、PyQGISを使ったプログラミングについてもっと学んだり、開発努力が重複していないか調べたりできます。
プラグインファイル¶
ここで例として見ていくプラグインのディレクトリ構造はこのようになります。
PYTHON_PLUGINS_PATH/
MyPlugin/
__init__.py --> *required*
mainPlugin.py --> *core code*
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
= プラグインの起点です。classFactory()
メソッドが必須ですが、それ以外にもどんな初期化コードでも含むことができます。操作操作操作:file:mainPlugin.py = プラグインの中心として作動するコードです。プラグインの全ての機能に関する情報と主要コードを含みます。
resources.qrc
= Qt Designerによって作られる .xmlドキュメントです。外観のリソースへの相対パスを含みます。resources.py
= 上記の .qrc ファイルがPythonへと変換されたものです。form.ui
= Qt Designerによって作られたGUIです。form.py
= 上記のform.ui がPythonへと変換されたものです。metadata.txt
= プラグインのウェブサイトとインフラで使われる一般的な情報、バージョン、名前、その他のメタデータを含みます。
ここ に、典型的なQGIS Pythonプラグインの基本的なファイル(スケルトン:骨組み)を、オンラインで自動的に作る手段があります。
Plugin Builder 3 という名前の、インターネット接続を必要とせずQGISプラグインのテンプレートを作ることのできるQGISプラグインもあります。3.x 互換のソースを生成するので、これはオススメの方法です。
警告
プラグインを Official Python plugin repository にアップロードする予定なら、プラグインの :ref:`official_pyqgis_repository_validation`で必要とされる幾つかの付加的なルールに、そのプラグインが従っていることを確認せねばなりません。
プラグインの内容¶
ここでは、上記のファイル構造中のそれぞれのファイルに何を書けばよいか、その情報と実例を提供します。
プラグインメタデータ¶
最初に、そのプラグインの名前や説明といった基本的な情報を、プラグインマネジャは検索する必要があります。metadata.txt
ファイルこそがその情報を置いておく場所になります。
注釈
メタデータのエンコーディングはすべてUTF-8でなければなりません。
メタデータ名 |
必須 |
注 |
---|---|---|
name |
Y |
そのプラグインの名前から成る短い文字列 |
qgisMinimumVersion |
Y |
最小QGISバージョンをドット記法で |
qgisMaximumVersion |
N |
最大QGISバージョンをドット記法で |
description |
Y |
プラグインを説明する短いテキスト。HTMLは不可 |
about |
Y |
プラグインの詳細を説明するより長いテキスト。HTMLは不可 |
version |
Y |
バージョンをドット記法で記した短い文字列 |
author |
Y |
著者の名前 |
Y |
著者のEメール。ウェブサイトでログインしたユーザのみに表示されるが、プラグインをインストールした後はプラグインマネジャで見ることができる |
|
changelog |
N |
文字列。改行して複数行になってもよい。HTML不可 |
experimental |
N |
boolean flag, True or False - True if this version is experimental |
deprecated |
N |
True か False のいずれかの値。単にアップロードしたバージョンに対してではなく、そのプラグインすべてに適用される |
tags |
N |
コンマで区切ったリスト。個々のタグの内部ではスペース可 |
homepage |
N |
プラグインのホームページを示す有効なURL |
repository |
Y |
ソースコードのリポジトリの有効なURL |
tracker |
N |
チケットとバグ報告のための有効なURL |
icon |
N |
画像のファイル名もしくは(プラグインの圧縮パッケージのベースフォルダからの)相対パス。画像はウェブに適したフォーマット(PNG, JPEG)で |
category |
N |
Raster、Vector、Database、Web のうちのいずれか |
plugin_dependencies |
N |
PIP-like comma separated list of other plugins to install |
server |
N |
boolean flag, True or False, determines if the plugin has a server interface |
hasProcessingProvider |
N |
boolean flag, True or False, determines if the plugin provides processing algorithms |
初期設定ではプラグインは プラグイン メニューの中に配置されます(メニューエントリにあなたのプラグインを追加する方法は次のセクションで見ます)が、
メニューや メニュー、 メニュー、 メニューの中に配置することもできます。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
注釈
If qgisMaximumVersion is empty, it will be automatically set to the major version plus .99 when uploaded to the Official Python plugin repository.
An example for this metadata.txt
; the next section is mandatory
[general]
name=HelloWorld
email=me@example.com
author=Just Me
qgisMinimumVersion=3.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
tracker=http://bugs.itopen.it
repository=http://www.itopen.it/repo
; 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=https://www.itopen.it
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=3.99
__init__.py¶
This file is required by Python's import system. Also, QGIS requires that this
file contains a classFactory()
function, which is called when the
plugin gets loaded into QGIS. It receives a reference to the instance of
QgisInterface
and must return an object 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 qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
# initialize Qt resources from file resources.py
from . 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")
self.action.triggered.connect(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
self.iface.mapCanvas().renderComplete.connect(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
self.iface.mapCanvas().renderComplete.disconnect(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 QGIS interfaceinitGui()
--> called when the plugin is loadedunload()
--> called when the plugin is unloaded
In the above example, addPluginToMenu
is used.
This will add the corresponding menu action to the
menu. Alternative methods exist to add the action to a different menu. Here is
a list of those methods:
All of them have the same syntax as the
addPluginToMenu
method.
Adding your plugin menu to one of those predefined method is recommended to keep consistency in how plugin entries are organized. However, you can add your custom menu group directly to the menu bar, as the next example demonstrates:
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")
self.action.triggered.connect(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()
Don't forget to set QAction
and QMenu
objectName
to a name
specific to your plugin so that it can be customized.
Resource File¶
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 pyrcc5 command:
pyrcc5 -o resources.py resources.qrc
注釈
In Windows environments, attempting to run the pyrcc5 from
Command Prompt or Powershell will probably result in the error "Windows
cannot access the specified device, path, or file [...]". The easiest
solution is probably to use the OSGeo4W Shell but if you are comfortable
modifying the PATH environment variable or specifiying the path to the
executable explicitly you should be able to find it at
<Your QGIS Install Directory>\bin\pyrcc5.exe
.
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.
When working on a real plugin it's wise to write the plugin in another (working) directory and create a makefile which will generate UI + resource files and install the plugin into your QGIS installation.
Documentation¶
The documentation for the plugin can be written as HTML help files. The
qgis.utils
module provides a function, showPluginHelp()
which
will open the help file browser, in the same way as other QGIS help.
The showPluginHelp()
function looks for help files in the same
directory as the calling module. It will look for, in turn,
index-ll_cc.html
, index-ll.html
, index-en.html
,
index-en_us.html
and index.html
, displaying whichever it finds
first. Here ll_cc
is the QGIS locale. This allows multiple translations of
the documentation to be included with the plugin.
The showPluginHelp()
function can also take parameters packageName,
which identifies a specific plugin for which the help will be displayed,
filename, which can replace "index" in the names of files being searched,
and section, which is the name of an html anchor tag in the document
on which the browser will be positioned.
Translation¶
With a few steps you can set up the environment for the plugin localization so that depending on the locale settings of your computer the plugin will be loaded in different languages.
Software requirements¶
The easiest way to create and manage all the translation files is to install Qt Linguist. In a Debian-based GNU/Linux environment you can install it typing:
sudo apt install qttools5-dev-tools
Files and directory¶
When you create the plugin you will find the i18n
folder within the main
plugin directory.
All the translation files have to be within this directory.
.pro file¶
First you should create a .pro
file, that is a project file that can be
managed by Qt Linguist.
In this .pro
file you have to specify all the files and forms you want to
translate. This file is used to set up the localization files and variables.
A possible project file, matching the structure of our
example plugin:
FORMS = ../form.ui
SOURCES = ../your_plugin.py
TRANSLATIONS = your_plugin_it.ts
Your plugin might follow a more complex structure, and it might be distributed
across several files. If this is the case, keep in mind that pylupdate5
,
the program we use to read the .pro
file and update the translatable string,
does not expand wild card characters, so you need to place every file explicitly
in the .pro
file.
Your project file might then look like something like this:
FORMS = ../ui/about.ui ../ui/feedback.ui \
../ui/main_dialog.ui
SOURCES = ../your_plugin.py ../computation.py \
../utils.py
Furthermore, the your_plugin.py
file is the file that calls all the menu
and sub-menus of your plugin in the QGIS toolbar and you want to translate them
all.
Finally with the TRANSLATIONS variable you can specify the translation languages you want.
警告
Be sure to name the ts
file like your_plugin_
+ language
+ .ts
otherwise the language loading will fail! Use the 2 letter shortcut for the
language (it for Italian, de for German, etc...)
.ts file¶
Once you have created the .pro
you are ready to generate the .ts
file(s)
for the language(s) of your plugin.
Open a terminal, go to your_plugin/i18n
directory and type:
pylupdate5 your_plugin.pro
you should see the your_plugin_language.ts
file(s).
Open the .ts
file with Qt Linguist and start to translate.
.qm file¶
When you finish to translate your plugin (if some strings are not completed the
source language for those strings will be used) you have to create the .qm
file (the compiled .ts
file that will be used by QGIS).
Just open a terminal cd in your_plugin/i18n
directory and type:
lrelease your_plugin.ts
now, in the i18n
directory you will see the your_plugin.qm
file(s).
Translate using Makefile¶
Alternatively you can use the makefile to extract messages from python code and Qt dialogs, if you created your plugin with Plugin Builder. At the beginning of the Makefile there is a LOCALES variable:
LOCALES = en
Add the abbreviation of the language to this variable, for example for Hungarian language:
LOCALES = en hu
Now you can generate or update the hu.ts
file (and the en.ts
too)
from the sources by:
make transup
After this, you have updated .ts
file for all languages set in the LOCALES
variable.
Use Qt Linguist to translate the program messages.
Finishing the translation the .qm
files can be created by the transcompile:
make transcompile
You have to distribute .ts
files with your plugin.
Load the plugin¶
In order to see the translation of your plugin just open QGIS, change the language (
) and restart QGIS.You should see your plugin in the correct language.
警告
If you change something in your plugin (new UIs, new menu, etc..) you have to
generate again the update version of both .ts
and .qm
file, so run
again the command of above.
Tips and Tricks¶
Plugin Reloader¶
During development of your plugin you will frequently need to reload it in QGIS for testing. This is very easy using the Plugin Reloader plugin. You can find it as an experimental plugin with the Plugin Manager.
Accessing Plugins¶
You can access all the classes of installed plugins from within QGIS using python, which can be handy for debugging purposes.:
my_plugin = qgis.utils.plugins['My Plugin']
Log Messages¶
Plugins have their own tab within the ログメッセージパネル.