Il est possible de créer des extensions dans le langage de programmation Python. Comparé aux extensions classiques développées en C++, celles-ci devraient être plus faciles à écrire, comprendre, maintenir et distribuer du fait du caractère dynamique du langage python.
Python plugins are listed together with C++ plugins in QGIS plugin manager.
They’re being searched for in these paths:
Écriture d’une extension
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. QGIS team also maintains an Dépôt officiel des extensions Python.
Ready to create a plugin but no idea what to do? Python Plugin Ideas wiki page lists wishes from the community!
Fichiers de l’extension
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*
A quoi correspondent ces fichiers?
Here
is an online automated way of creating the basic files (skeleton) of a typical
QGIS Python plugin.
Also there is a QGIS plugin called Plugin Builder that creates plugin template from QGIS and doesn’t require internet connection.
This is the recommended option, as it produces 2.0 compatible sources.
Contenu de l’extension
Ici vous pouvez trouver des informations et des exemples sur ce qu’il faut ajouter dans chacun des fichiers de la structure de fichiers décrite ci-dessus.
__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 resouces.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 ``:func:`addPluginToMenu`<http://qgis.org/api/classQgisInterface.html#ad1af604ed4736be2bf537df58d1399c3>`_ 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()
Tous ont la même syntaxe que la méthode addPluginToMenu().
Ajouter votre extension dans un des menus prédéfinis est une méthode recommandée pour conserver la cohérence de l’organisation des entrées d’extensions. Toutefois, vous pouvez ajouter votre propre groupe de menus directement à la barre de menus, comme le montre l’exemple suivant:
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()
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 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.
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 to your QGIS installation.
Documentation
La documentation sur l’extension peut être écrite sous forme de fichiers d’aide HTML. Le module qgis.utils fournit une fonction, showPluginHelp(), qui ouvrira le fichier d’aide dans un navigateur, de la même manière que pour l’aide de QGIS.
La fonction showPluginHelp`() recherche les fichiers d’aide dans le même dossier que le module d’appel. elle recherchera, dans l’ordre, index-ll_cc.html, index-ll.html, index-en.html, index-en_us.html et index.html, affichant celui qu’elle trouve en premier. Ici, ll_cc est pour la locale de QGIS. Ceci permet d’inclure des traductions multiples dans la documentation de l’extension.
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.