Desenvolvimento de Complementos Python

É possível criar plugins usando a linguagem de programação Python. Em comparação com plugins clássicos criados em C++, esses devem ser mais fáceis de escrever, entender, manter e distribuir devido à natureza dinâmica da linguagem 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 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) (on Windows XP or earlier) or C:\Users\(user). Since QGIS 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.

Nota

By setting QGIS_PLUGINPATH to an existing directory path, you can add this path to the list of paths that are searched for plugins.

Passos:

  1. Ideia: Tenha uma ideia sobre o que você quer fazer com seu novo plugin QGIS. Por que você quer fazê-lo? Qual problema você gostaria de resolver? Já existe outro plugin para este tipo de problema?

  2. Create files: Create the files described next. A starting point (__init__.py). Fill in the Plugin metadados (metadata.txt) A main python plugin body (mainplugin.py). A form in QT-Designer (form.ui), with its resources.qrc.
  3. Write code: Write the code inside the mainplugin.py
  4. Test: Close and re-open QGIS and import your plugin again. Check if everything is OK.
  5. Publish: Publish your plugin in QGIS repository or make your own repository as an “arsenal” of personal “GIS weapons”.

Escrevendo um complemento

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 Repositório oficial de complementos python. Ready to create a plugin but no idea what to do? Python Plugin Ideas wiki page lists wishes from the community!

arquivos de complementos

Está é a estrutura de diretórios do nosso exemplo de complemento

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*

Qual o significado dos arquivos:

  • __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 = A tradução do arquivo .qrc descrito acima para Python.

  • form.ui = A GUI creiada pelo Qt Designer.

  • form.py = A tradução do formulário .ui descrito acima para Python.

  • metadata.txt = Required for QGIS >= 1.8.0. Containts general info, version, name and some other metadata used by plugins website and plugin infrastructure. Since QGIS 2.0 the metadata from __init__.py are not accepted anymore and the metadata.txt is required.

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.

Aviso

If you plan to upload the plugin to the Repositório oficial de complementos python you must check that your plugin follows some additional rules, required for plugin Validação

Conteúdo do complemento

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

Plugin metadados

First, 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.

Importante

Todos os metadados devem estar codificados em UTF-8.

Nome metadados

requerida

Notas

Nome

Verdadeiro

a short string containing the name of the plugin
qgisMinimumVersion

Verdadeiro

dotted notation of minimum QGIS version
qgisMaximumVersion

Falso

versão QGIS máxima com notação pontilhada

Descrição

Verdadeiro

texto pequeno que descreve o complemento, HTML não é permitido

sobre

Falso

texto longo que descreve o complemento em detalhes, HTML não é permitido

Versão

Verdadeiro

caracteres curtos com a versão com notação pontilhada

Autor

Verdadeiro

nome do autor

email

Verdadeiro

email of the author, will not be shown on the web site
changelog

Falso

string, can be multiline, no HTML allowed
experimental

Falso

valor booleano, True ou False

desaprovado

Falso

valor booleano,`True` ou False`, aplica-se a todo o plugin e não apenas para a versão carregada

etiquetas

Falso

lista separada por vírgulas, espaços são permitidos dentro das etiquetas individuais

página inicial

Falso

uma URL válida apontando para a página inicial do seu plugin

Repositório

Falso

uma URL válida para repositório do código fonte

rastreador

Falso

uma URL válida para o reporte de chamadas e erros

Ícone

Falso

a file name or a relative path (relative to the base folder of the plugin’s compressed package)

Categoria

Falso

one of Raster, Vector, Database and 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

Nota

If qgisMaximumVersion is empty, it will be automatically set to the major version plus .99 when uploaded to the Repositório oficial de complementos python.

Um exemplo para este metadata.txt

; the next section is mandatory

[general]
name=HelloWorld
email=me@example.com
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, QGIS 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__ –> Dá acesso à interface QGIS

  • initGui() –> chamada quando o complemento é carregado

  • unload()` –> chamada quando o complemento é descarregado

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

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")
    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.

Arquivo de Recursos

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

E isso é tudo... nada complicado :)

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.

Documentação

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.