16.1. Structuring Python Plugins

Voici quelques étapes à suivre afin de créer des extensions:

  1. Idea: Have an idea about what you want to do with your new QGIS plugin. Why do you do it? What problem do you want to solve? Is there already another plugin for that problem?

  2. Create files: some are essentials (see Fichiers de l’extension)

  3. Écrire le code: écrire le code dans les fichiers appropriés

  4. Tester: Rechargez votre extension pour vérifier si tout est OK

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

16.1.1. Ecriture d’un plugin

Since the introduction of Python plugins in QGIS, a number of plugins have appeared. The QGIS team maintains an Dépôt officiel des extensions QGIS. You can use their source to learn more about programming with PyQGIS or find out whether you are duplicating development effort.

16.1.1.1. Fichiers de l’extension

Voici la structure du dossier pour notre plugin servant d’exemple

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*

Quelle est la signification de ces fichiers:

  • __init__.py = The starting point of the plugin. It has to have the classFactory() method and may have any other initialisation code.

  • mainPlugin.py = The main working code of the plugin. Contains all the information about the actions of the plugin and the main code.

  • resources.qrc = The .xml document created by Qt Designer. Contains relative paths to resources of the forms.

  • resources.py = The translation of the .qrc file described above to Python.

  • form.ui = l’interface conçue sur Qt Designer

  • form.py = The translation of the form.ui described above to Python.

  • metadata.txt = Contains general info, version, name and some other metadata used by plugins website and plugin infrastructure.

Here is a way of creating the basic files (skeleton) of a typical QGIS Python plugin.

There is a QGIS plugin called Plugin Builder 3 that creates a plugin template for QGIS. This is the recommended option, as it produces 3.x compatible sources.

Avertissement

If you plan to upload the plugin to the Dépôt officiel des extensions QGIS you must check that your plugin follows some additional rules, required for plugin Validation

16.1.2. Contenu de l’extension

Here you can find information and examples about what to add in each of the files in the file structure described above.

16.1.2.1. Métadonnées de l’extension

First, the plugin manager needs to retrieve some basic information about the plugin such as its name, description etc. File metadata.txt is the right place to put this information.

Note

Toutes les métadonnées doivent être encodées en UTF-8.

Nom des métadonnées

Requis

Notes

Nom

Vrai

une courte chaîne de caractères contenant le nom du plugin

Version minimale de QGIS

Vrai

dotted notation of minimum QGIS version

Version maximale de QGIS

Faux

dotted notation of maximum QGIS version

description

Vrai

short text which describes the plugin, no HTML allowed

au sujet

Vrai

longer text which describes the plugin in details, no HTML allowed

version

Vrai

short string with the version dotted notation

auteur

Vrai

nom de l’auteur

e-mail

Vrai

email of the author, only shown on the website to logged in users, but visible in the Plugin Manager after the plugin is installed

Suivi des modifications

Faux

de type texte, indique les modifications de version. Peut être multiligne, le HTML n’est pas autorisé

experimental

Faux

booléen, True ou False, indiquant si cette version est expérimentale

deprecated

Faux

booléen, True ou False permettant de savoir si l’extension est obsolète ou pas. S’applique à toute l’extension.

les mots-clé

Faux

comma separated list, spaces are allowed inside individual tags

page d’accueil

Faux

a valid URL pointing to the homepage of your plugin

repository

Vrai

une URL valide du dépôt du code

tracker

Faux

une URL valide pour le signalement des bugs et demandes

icon

Faux

a file name or a relative path (relative to the base folder of the plugin’s compressed package) of a web friendly image (PNG, JPEG)

category

Faux

soit Raster, Vector, Database ou Web

plugin_dependencies

Faux

PIP-like comma separated list of other plugins to install

serveur

Faux

boolean flag, True or False, determines if the plugin has a server interface

hasProcessingProvider

Faux

boolean flag, True or False, determines if the plugin provides processing algorithms

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 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

Note

If qgisMaximumVersion is empty, it will be automatically set to the major version plus .99 when uploaded to the Dépôt officiel des extensions QGIS.

Un exemple pour ce fichier 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

; Since QGIS 3.8, a comma separated list of plugins to be installed
; (or upgraded) can be specified.
; The example below will try to install (or upgrade) "MyOtherPlugin" version 1.12
; and any version of "YetAnotherPlugin"
plugin_dependencies=MyOtherPlugin==1.12,YetAnotherPlugin

16.1.2.2. __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

16.1.2.3. 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__ » qui permet l’accès à l’interface de QGIS

  • initGui() called when the plugin is loaded

  • unload() called when the plugin is unloaded

In the above example, 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:

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.

16.1.2.4. 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

Note

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.

16.1.3. 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.

16.1.4. Traduction

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.

16.1.4.1. 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

16.1.4.2. Fichiers et répertoire

Lorsque vous créez l’extension, vous devriez trouver le répertoire « i18n » dans le répertoire principal de l’extension.

Tous les fichiers de traduction doivent être dans ce répertoire.

16.1.4.2.1. Fichier .pro

Premièrement, vous devez créer un fichier « .pro ». Il s’agit d’un fichier projet qui peut être géré par 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.

Enfin, avec la variable « TRANSLATIONS », vous pouvez spécifier les langages de traduction que vous souhaitez.

Avertissement

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…)

16.1.4.2.2. Fichier .ts

Once you have created the .pro you are ready to generate the .ts file(s) for the language(s) of your plugin.

Lancez un terminal, allez au dossier your_plugin/i18n et saisissez:

pylupdate5 your_plugin.pro

Vous devriez voir le(s) fichier(s) your_plugin_language.ts.

Open the .ts file with Qt Linguist and start to translate.

16.1.4.2.3. Fichier .qm

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

Vous devriez maintenant voir le(s) fichier(s) your_plugin.qm dans le dossier i18n.

16.1.4.3. Traduction en utilisant un fichier 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.

16.1.4.4. Chargement de l’extension

In order to see the translation of your plugin, open QGIS, change the language (Settings ‣ Options ‣ General) and restart QGIS.

Vous devriez voir votre plugin dans la bonne langue.

Avertissement

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.

16.1.5. Conseils et Astuces

16.1.5.1. 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 with the Plugin Manager.

16.1.5.2. 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']

16.1.5.3. Log Messages

Plugins have their own tab within the Journal des messages (log).

16.1.5.4. Partage de votre extension

QGIS is hosting hundreds of plugins in the plugin repository. Consider sharing yours! It will extend the possibilities of QGIS and people will be able to learn from your code. All hosted plugins can be found and installed from within QGIS with the Plugin Manager.

Informations et prérequis consultables ici: plugins.qgis.org.