Creating a Processing Toolbox plugin
The QGIS Processing Toolbox provides a powerful set of algorithms for QGIS Python programming, which we'll see throughout this book. You add your own scripts to the toolbox, and with the latest version of QGIS, you can now turn those scripts into plugins. You can install these plugins like any other QGIS plugin using Plugin Manager and then have those scripts appear in Processing Toolbox. This process is significantly easier than writing a traditional plugin from scratch.
Getting ready
First you need a script to package as a plugin. You can package multiple scripts into a single plugin, but to keep things simple, use one. This sample script will save the current map view as an image. Create the script using the following steps:
- In Processing Toolbox, expand the Scripts tree.
- Double-click on the Create new script tool.
- In the script editor, add the following code, specifying an output directory for your map images:
from qgis.utils import iface import datetime c = iface.mapCanvas() t = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now()) img_path = '<output directory>/map{}.png' c.saveAsImage(img_path.format(t), None, 'PNG')
- Click on the Save As icon to save the image in your scripts directory as
MapImage.py
. - The script will then appear in the User Scripts tree under Scripts in Processing Toolbox.
- Set up a map view and then double-click on the script to verify that an image has been created in the output directory.
How to do it...
Now you are ready to create the plugin from your sample script:
- Under the script tools section in Processing Toolbox, double-click on Create script collection plugin.
- Fill out the metadata fields in the dialog.
- Ensure the MapImage script is checked in the Script selector dialog.
- When you navigate to the output folder, create a new folder called
MapImage
: - Click on the OK button
- Navigate to the output folder and verify the plugin files were created.
How it works...
From a functional perspective, all the script does is copy the files to your user scripts directory. But the plugin packaging allows you to distribute your work to other users using the QGIS plugin framework.
There's more...
The Processing Toolbox has a script manager similar to the QGIS plugin manager, in which you can download scripts written by other users for processing, or as examples to write your own scripts. To access this script manager, expand the Scripts menu in the Processing Toolbox, then expand the Tools menu, and finally double-click Get scripts from on-line scripts collection. From there, you can browse a list of downloadable scripts.