Version 1/4
-
Next » -
Current version
Redmine Admin, 11/23/2011 04:44 pm
Fixed broken PyQt link
Architecture for Python plugins is still in development and things may change.
Developing plugins with Python requires QGIS 0.9.0 or newer version. This tutorial requires QGIS 1.0.0 and higher!
This document assumes that you're already familiar with:
If not, please check the appropriate documentation.
More information on writing Python Plugins can be found in the PyQGIS Cookbook.
Introduction¶
With development of PythonBindings for QGIS it's now possible to create plugins in Python programming language. In comparison with classical plugins written in C++ these should be easier to write, understand and maintain due the nature of the language.
Note that you must compile QGIS with optional Python support or specific binding should be installed.
Python plugins are listed together with C++ plugins in QGIS plugin manager. They're being searched for in these paths:
- UNIX/Mac: ~/.qgis/python/plugins and (qgis_prefix)/share/qgis/python/plugins
- Windows: ~/.qgis/python/plugins and (qgis_prefix)/python/plugins
Home directory (denoted by above ~) on Windows is usually something like C:\Documents and Settings\(user).
Subdirectories of these paths are considered as Python packages that can be imported to QGIS as plugins.
Steps¶
- 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?
- Create files: Create the files described nrxt. A starting point (init.py). A main python plugin body(plugin.py). A form in QT-Designer (form.ui), with it's resources.qrc.
- Write code: Write the code inside the plugin.py
- Test: Close and re-open QGIS and import your plugin again. Check if everything is OK.
- Publish: Publish your plugin in QGIS repository or make your own repository as an "arsenal" of personal "GIS weapons"
Writing a plugin¶
Since the introduction of python plugins in QGIS, a number of plugins have appeared - on PluginRepositories page you can find some of them, you can use their source to learn more about programming with PyQGIS or find out whether you're not duplicating development effort.
Ideas¶
Ready to create a plugin but no idea what to do? Python Plugin Ideas page lists wishes from the community!
Creating necessary files¶
Here's the directory structure of our example plugin:
PYTHON_PLUGINS_PATH/
testplug/
__init__.py
plugin.py
resources.qrc
resources.py
form.ui
form.py
- init.py = The starting point of the plugin. Contains general info, version, name and main class.
- plugin.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 = The GUI created by QT-Designer.
- form.py = The translation of the form.ui described above to Python.
Here and there are two automated ways of creating the basic files (skeleton) of a typical QGIS Python plugin. Useful to help you start with a typical plugin.
Writing code¶
init.py
First, plugin manager needs to retrieve some basic information about the plugin such as its name, description etc. File init.py is the right place where to put this information:
#!python def name(): return "My testing plugin" def description(): return "This plugin has no real use." def version(): return "Version 0.1" def qgisMinimumVersion(): return "1.0" def authorName(): return "Developer" def classFactory(iface): # load TestPlugin class from file testplugin.py from testplugin import TestPlugin return TestPlugin(iface)
The Plugin .py
One thing worth mentioning is 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 - in our case it's called TestPlugin. This is how should this class look like (e.g. testplugin.py):
#!python
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.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!"
Only functions of the plugin that must exist are initGui() and unload(). These functions are called when plugin is loaded and unloaded.
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's good to use a prefix that won't collide with other plugins or any parts of QGIS, otherwise you might get resources you didn't 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 plugin manager and see a message in console when toolbar icon or appopriate 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
This documentation method requires Qgis version 1.5
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 users 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.
Code Snippets
This section features code snippets to facilitate plugin development.
How to call a method by a key shortcut
In the plug-in add to the initGui():
self.keyAction = QAction("Test Plugin", self.iface.mainWindow())
self.iface.registerMainWindowAction(self.keyAction, "F7") # action1 is triggered by the F7 key
self.iface.addPluginToMenu("&Test plugins", self.keyAction)
QObject.connect(self.keyAction, SIGNAL("triggered()"),self.keyActionF7)
To unload() add:
self.iface.unregisterMainWindowAction(self.keyAction)
The method that is called when F7 is pressed:
def keyActionF7(self): QMessageBox.information(self.iface.mainWindow(),"Ok", "You pressed F7")
How to toggle Layers
In QGIS >= 1.5 you can access the legend through legendInterface(). There you can control layer visibility like this:
from PyQt4 import QtCore, QtGui
from qgis import core, gui
i = qgis.utils.iface
# load a georeferenced raster layer
loadedLayer = i.addRasterLayer('c:\\data\\a_map.png')
# get legend
legend = i.legendInterface()
# check current visibility
legend.isLayerVisible(loadedLayer)
# set visibility off
legend.setLayerVisible(loadedLayer, False)
# and on again!
legend.setLayerVisible(loadedLayer, True)
_*Code contributed by user Diethard in QGIS Forum
How to toggle Layers (work around for QGIS < 1.5)
As there is currently no method to directly access the layers in the legend, here is a workaround how to toggle the layers using layer transparency.
def toggleLayer(self, lyrNr):
lyr = self.iface.mapCanvas().layer(lyrNr)
if(lyr):
cTran = lyr.getTransparency()
if cTran > 100:
lyr.setTransparency(0)
else:
lyr.setTransparency(255)
self.iface.mapCanvas().refresh()
The method requires the layer number (0 being the top most) and can be called by:
self.toggleLayer(3)
How to access attribute table of selected features
How to access attribute table of selected features
def changeValue(self, value):
layer = self.iface.activeLayer()
if(layer):
nF = layer.selectedFeatureCount()
if (nF > 0):
layer.startEditing()
ob = layer.selectedFeaturesIds()
b = QVariant(value)
if (nF > 1):
for i in ob:
layer.changeAttributeValue(int(i),1,b) # 1 being the second column
else:
layer.changeAttributeValue(int(ob[0]),1,b) # 1 being the second column
layer.commitChanges()
else:
QMessageBox.critical(self.iface.mainWindow(),"Error", "Please select at least one feature from current layer")
else:
QMessageBox.critical(self.iface.mainWindow(),"Error","Please select a layer")
The method requires the one parameter (the new value for the attribute field of the selected feature(s)) and can be called by:
self.changeValue(50)
How to debug a plugin using PDB
First add this code in the spot where you would like to debug:
# Use pdb for debugging import pdb # These lines allow you to set a breakpoint in the app pyqtRemoveInputHook() pdb.set_trace()
Then run QGIS from the command line.
On Linux do:
$ ./Qgis
On Mac OS X do:
$ /Applications/Qgis.app/Contents/MacOS/Qgis
And when the application hits your breakpoint you can type in the console!
Testing¶
Releasing the plugin¶
Once your plugin is ready and you think the plugin could be helpful for some people, don't hesitate to upload it to PyQGIS plugin repository. On that page you can find also packaging guidelines how to prepare the plugin to work well with the plugin installer. Or in case you'd like to set up your own plugin repository, create a simple XML file that will list the plugins and their metadata, for examples see other PluginRepositories.
Creating Your Own Repository¶
You may wish to create your own repository for a variety of reasons including testing. You will need to be able to load the following files onto a website (use your own names, but the extension/file type matters):- yourInstallInstructions.xml
- yourSchema.xsl (optional)
- yourPlugin.zip
Installation Instructions
Your installation instructions are defined in an XML file loaded into the web root directory that is to be your repository. The following is an example to get you going.
<?xml version = '1.0' encoding = 'UTF-8'?>
<?xml-stylesheet type="text/xsl" href="yourSchema.xsl" ?>
<plugins>
<pyqgis_plugin name="A plugin" version="0.1">
<qgis_minimum_version>1.6</qgis_minimum_version>
<description>A few words</description>
<homepage>http://www.aplugin.org</homepage>
<file_name>myFirst.zip</file_name>
<author_name>Aplugin Writer</author_name>
<download_url>http://www.aplugin.org/files/myFirst.zip</download_url>
</pyqgis_plugin>
<pyqgis_plugin name="Another plugin" version="1.5">
<qgis_minimum_version>1.7</qgis_minimum_version>
<description>Something useful</description>
<homepage>http://www.aplugin.org</homepage>
<file_name>tools.zip</file_name>
<author_name>Aplugin Writer</author_name>
<download_url>http://www.aplugin.org/files/tools.zip</download_url>
</pyqgis_plugin>
</plugins>
The second line defining a schema file is only necessary if you want to provide a browser view of your download page. You can leave it out and QGIS will still be able to install your plugins.
Each plugin need a name, version, description and author - these will be the text as displayed for your plugin by QGIS's installer.
You need to provide a minimum QGIS version number to ensure that QGIS doesn't try to run it on an incompatible build.
Does anyone know why the file_name is included?
The download_url provides the file web address. In this example it can be seen that the file is in a subdirectory of the repository.
A repository can contain one or more plugins available for download. Each plugin needs their own definition.
Schema (optional)
The schema file is optional but, when included, allows users to browse your website and get a basic explanation about your plugins.
This schema will list your plugins with simple headings.
<nowiki>
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/plugins">
<html>
<head>
<title>QGIS Plugins</title>
<style>
body {
font-family:Verdana, Arial, Helvetica, sans-serif;
width: 50em;
}
div.plugin {
background-color:#C0FFFF;
border:1px solid #0000FF;
clear:both;
display:block;
padding:0 0 0.5em;
margin:1em;
}
div.head {
background-color:#01AFFF;
border-bottom-width:0;
color:#FFF;
display:block;
font-size:110%;
font-weight:bold;
margin:0;
padding:0.3em 1em;
}
div.description{
display: block;
float:none;
margin:0;
text-align: left;
padding:0.2em 0.5em 0.4em;
color: black;
font-size:100%;
font-weight:normal;
}
div.download, div.author{
font-size: 80%;
padding: 0em 0em 0em 1em;
}
</style>
</head>
<body>
<h1>QGIS plugins</h1>
<xsl:for-each select="/plugins/pyqgis_plugin">
<div class="plugin">
<div class="head">
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="homepage" />
</xsl:attribute>
<xsl:value-of select="@name" /> : <xsl:value-of select="@version" />
</xsl:element>
</div>
<div class="description">
<xsl:value-of select="description" />
</div>
<div class="download">
Download:
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="download_url" />
</xsl:attribute>
<xsl:value-of select="file_name" />
</xsl:element>
</div>
<div class="author">
Author: <xsl:value-of select="author_name" />
</div>
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</nowiki>
Just save the schema file (with a .xsl extension) to the root directory of your repository along with the XML installation instructions.
The Plugin
This is a zip file containing everything that makes up your working project. You don't need to include the .pyc files as they will be regenerated the first time your plugin runs.
While not necessary to allow the plugin to work, it is helpful to anyone who wishes to develop or learn from your work if you also include additional files such as .ui (GUI definitions), .qrc (resources), change logs and makefiles.
The zip file gets expanded 'as is' into the QGIS plugins directory. Your zip file therefore needs to contain the top level directory of your plugin with all your files and subdirectories contained within this directory.
Remark: Configuring Your IDE on Windows¶
On Linux there is no additional configuration needed to develop plug-ins.
But on Windows you need to make sure you that you have the same environment settings and use the same libraries and interpreter as qgis.
The fasted way to do this, is to modify the startup batch file of qgis.
If you used the OSGeo4W Installer, you can find this under the bin folder of your OSGoeW install. Look for something like C:\OSGeo4W\bin\qgis-unstable.bat.
I will illustrate how to set up the pyscripter IDE (http://code.google.com/p/pyscripter). Other IDE’s might require a slightly different approach:
- Make a copy of qgis-unstable.bat and rename it pyscripter.bat.
- Open it in an editor. And remove the last line, the one that starts qgis.
- Add a line that points to the your pyscripter executable and add the commandline argument that sets the version of python to be used, in version 1.3 of qgis this is python 2.5.
- Also add the argument that points to the folder where pyscripter can find the python dll used by qgis, you can find this under the bin folder of your OSGeoW install.
@echo off SET OSGEO4W_ROOT=C:\OSGeo4W call "%OSGEO4W_ROOT%"\bin\o4w_env.bat call "%OSGEO4W_ROOT%"\bin\gdal16.bat @echo off path %PATH%;%GISBASE%\bin Start C:\pyscripter\pyscripter.exe --python25 --pythondllpath=C:\OSGeo4W\bin
Now when you double click this batch file, it will start pyscripter.