Page 1 of 73 (1442 posts)

  • talks about »


Last update:
Thu Mar 5 05:50:08 2015

A Django site.

QGIS Planet

Get your QGIS merchandise while it’s hot!

Since the 2.8 release is done, the QGIS team has been busy with a small side project: setting up a series of shops for fans of QGIS. Right now, the following shops are available:

North America

There is a US and a Canadian shop. Additionally, there is also the possibility to design your own products (US, Canada).



There’s also a series of European shops, for example for the UK, Germany, and France. There are more, if Spreadshirt has a site for your country, there’s probably a QGIS shop too.

For each product sold, the QGIS project receives around $3 (minus applicable fees) which will go directly towards improving your favorite GIS.

Upcoming User Group Meetings

There are two upcoming user group meetings – one in Edinburgh and one in London. Tickets are available through Eventbrite. If you want to attend the Scottish event, click here, or if the South East is closer then click here.

As ever, we are always keen to hear from the users and if you have something you would like to share with the rest of the user group then please get in touch.  Lightning talks or longer 20 minute presentations welcomed.

QGIS 2.8 LTR has landed


It’s finally here! QGIS 2.8 LTR “Wien” is officially available for download now.

What’s an LTR

LTR stands for “Long Term Release”. This means that QGIS now has a system in place to provide a one-year stable release with backported bug fixes. The idea behind LTR is to have a stable platform for enterprises and organizations that don’t want update their software and training materials more often than once a year. To make the LTR a success, users and developers alike should be aware that bug fixes should be applied to both the LTR branch as well as the normal development branch. If you are interested in the details, you can find more info in the corresponding QGIS Enhancement Proposal.

Users who enjoy working with the cutting-edge version will be able to follow the regular four-monthly release cycle like last year.

What’s new?

This new version comes with many great new features which you can explore in the official visual changelog. It’s really hard to pick but my personal favorites are:

On the layer styling front, there are two great additions: raster image fills and a live heatmap renderer which makes it possible to create dynamic heatmaps on the fly.

raster image fill

Raster image fill symbol layer type

Another feature I’m sure many of you will enjoy is the support for custom prefixes for joins.

Custom join prefixes

Custom join prefixes

Last but not least, I want to point your attention to the great improvements to the rule-based legend which is now structured in a nice tree.

Rule-based renderer legend tree

Rule-based renderer legend tree

Don’t forget to check out the other new features!


None of this would have been possible without the great QGIS community and all the many different people involved in running the project. Thanks a lot to all of you and a special shout out for the sponsors! *applause*


How to create a QGIS PDF report with a few lines of python

Sometimes you want to automatically generate a report to reflect the latest state of your data. For example you may be capturing spatial data into a PostGIS database and want a snapshot of that every few hours expressed as a pdf report. This example shows you how you can quickly generate a pdf based on a QGIS project (.qgs file) and a QGIS template (.qpt file).

Using this approach you can generate all kinds of useful outputs without ever needing to open QGIS each time you generate the report. Simply create the needed project and template files and then run it like this:


QGIS Instant Print Plugin

As a side product of a customer project, we’re publishing a QGIS plugin for printing maps to a file with just two mouse clicks.

To use the instant print tool, a composer needs to be created first. The only requirement is that it contains exactly one map item.

The instant print tool can then be activated from the plugin toolbar by clicking on the plugin icon icon.

In the dialog window which appears, one can pick the composer to use as page layout. A selection rectangle is displayed in the map canvas, sized according to the size of the map item in the composer and the scale chosen in the instant print dialog. The selection rectangle can be freely dragged around to choose the region one wishes to print. When dragging the selection rectangle, the previous rectangle is shown shaded and can be used as a snap reference when setting the new region. While the instant print tool is active, the canvas can be panned with the middle mouse button.


To instant print tool can be installed with the QGIS plugin manager and the sources are available on Github.

Compiling OTB Orfeo ToolBox software on Centos/Scientific Linux

The Orfeo ToolBox (OTB), an open-source C++ library for remote sensing images processing, is offering a wealth of algorithms to perform Image manipulation, Data pre-processing, Features extraction, Image Segmentation and Classification, Change detection, Hyperspectral processing, and SAR processing.

Since there is no (fresh) RPM package available for Centos or Scientific Linux, here some quick hints (no full tutorial, though) how to get OTB easily locally compiled. We are following the Installation Chapter.

Importantly, you need to have some libraries installed including GDAL. Be sure that it has been compiled with the  –with-rename-internal-libtiff-symbols and  –with-rename-internal-libgeotiff-symbols flags to avoid namespace collision a.k.a segmentation fault of OTB as per “2.2.4 Building your own qualified Gdal“. We’ll configure and build with the GDAL-internal Tiff and Geotiff libraries that supports BigTiff files

# configure GDAL
./configure \
 --without-libtool \
 --with-geotiff=internal --with-libtiff=internal \
 --with-rename-internal-libtiff-symbols=yes \
 --with-rename-internal-libgeotiff-symbols=yes \
make install

The compilation of the OTB source code requires “cmake” and some other requirements which you can install via “yum install …”. Be sure to have the following structure for compiling OTB, i.e. store the source code in a subdirectory. The binaries will then be compiled in a “build” directory parallel to the OTB-SRC directory:

|-- build/
`-- OTB-SRC/
    |-- Applications/
    |-- CMake/
    |-- CMakeFiles/
    |-- Code/
    |-- Copyright/
    |-- Examples/
    |-- Testing/
    `-- Utilities/

Now it is time to configure everything for OTB. Since I didn’t want to bother with “ccmake”, below the magic lines to compile and install OTB into its own subdirectory within /usr/local/. We’ll use as many internal libraries as possible according to the table in the installation guide. The best way is to save the following lines as a text script “” for easier (re-)use, then run it:


mkdir -p build
cd build

cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr/local/otb-$OTBVER \

make -j4
# note: we assume to have write permission in /usr/local/otb-$OTBVER
make install

That’s it!

In order to use the freshly compiled OTB, be sure to add the new directories for the binaries and the libraries to your PATH and LD_LIBRARY_PATH variables, e.g. in $HOME/.bashrc:

export PATH=$PATH:/usr/local/bin:/usr/local/otb-4.4.0/bin
export LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64/:/usr/local/otb-4.4.0/lib/otb/

Enjoy OTB! And thanks to the OTB developers for making it available.

The post Compiling OTB Orfeo ToolBox software on Centos/Scientific Linux appeared first on GFOSS Blog | GRASS GIS Courses.

Dica para ajustar posição de símbolos em QGIS | Hack to adjust map symbols location in QGIS

De quando em vez aparecem-me zonas com demasiado símbolos no mesmo local, e pensei como seria fantástico se os pudesse arrastar para um local mais conveniente sem ter de alterar as suas geometrias, tal como é possível fazer com as etiquetas. Esse pensamento deu-me a ideia base para a dica que vou demonstrar.

Now and then I get too many map symbols (points) in the same place, and I thought how nice it would be if we could drag n’ drop them around without messing with their geometries position, just like we do with labels. That thought gave me an idea for a cool hack.

Escolha a sua camada de pontos e comece por criar dois novos campos chamados symbX e symbY (Tipo: Decimal; Tamanho: 20; precisão: 5). No separador “Estilo” das propriedades da camada, defina para cada nível do seu símbolo o seguinte: Escolher “unidade do mapa” como a unidade para as opções de afastamento; Usar a seguinte expressão na opção afastamento das propriedades definidas por dados.

Choose your point layer and start by creating two new fields called symbX and symbY (Type: Decimal number; Size: 20; Precision: 5). Now go the layer properties and in the Style tab edit your symbol. For each level of your symbol select “map units” as the offset units, and set the following expression in the offset data define properties option:

    tostring($x - symbX) + ',' + tostring($y - symbY)

Screenshot from 2015-02-22 18:18:43

Tenha atenção que, se as coordenadas do seu mapa tiver valores negativos, será necessário uma pequena alteração ao código. E. g., se tiver valores negativos em X deverá usar-se  antes a expressão “tostring(symbX -$x)”.

Beware that if your coordinates have negative values you need to adapt the code. E.g., If you have negative values in X you should use “tostring(symbX -$x)” instead.

De forma temporária coloque etiquetas na sua camada usando um texto pequeno (eu usei o ‘+’ (sinal de mais) centrado e com um buffer branco) e defina as coordenadas X e Y dos propriedades definidadas por dados usando os campos symbX e symbY,

Now, temporarly  label your layer with a small convenient text (I used a centered ‘+’ (plus sign) with a white buffer) and set its coordinates to data defined using the symbX and symbY Fields.

Screenshot from 2015-02-22 22:42:07

A partir desse momento, quando usar a ferramenta de mover etiquetas, não só alterará a posição da etiqueta, mas também a do próprio símbolo! Fantástico, não?

From this point on, when you use the move label tool, not only the label position change but also the actual symbol! Pretty cool, isn’t it?


Note que as geometria dos elementos não são alteradas durante o processo. Para além disso, lembre-se que neste caso também poderá adicionar linhas de guia para ligar os símbolos à posição original do ponto.

Notice that the features geometries are not changed during the process. Also, remember that in this case you can also add leading lines to connect the symbols to the original position of the points.

Loading MasterMap: Free, Easy and Fast

We've developed a new graphical loading tool for OS MasterMap data focussing on usability and performance to make it easy to load national Ordnance Survey MasterMap datasets in a matter of hours.

OS Translator II - Load OS MasterMap into PostGIS quickly, easily and for free

The tool is OS Translator II - it makes use of the excellent GDAL library and is available now in the official QGIS Plugins repository.

This blog post talks about some simple benchmarks we've carried out.


National load times were as follows:

  • MasterMap Topography (National) 20 hrs 21 mins 1
  • MasterMap ITN (National) < 6 mins

Installing PostgreSQL, PostGIS and QGIS took less than 10 minutes.

1 This is the most time-consuming test which filled the SSD on the first attempt. Importing to a tablespace on the main HDD completed after 20.3 hours but showed the import of tile 1592959-TR0585-5c3268.gz to have failed with this error. Until this issue is resolved the tile would need to be loaded and de-duplicated manually (e.g. using ogr2ogr to import and a SQL query to de-duplicate) to complete the dataset. De-duplication removes duplicate features caused by the chunking / supply process.

Comparison With Other Open Source Tools

We were curious as to how OS Translator II load times compared with other open loading methods so we did some basic tests using the "SU" tile of MasterMap Topography and ITN datasets and compared it with the popular Loader scripts. The results looked like this:

OS Translator II Benchmarks

Please note that OS Translator II had an unfair advantage in these tests as it automatically takes advantage of multiple-CPU cores whereas Loader presently does not.

Hardware and Software

We used the following hardware and software configuration:

  • CPU Intel Core i7 4790K (Haswell) @ 4GHz
  • Memory 32GB PC3-12800
  • Disk(s) Samsung 840 EVO 250GB SSD and Seagate Barracuda ST2000DM001 2TB HDD2
  • OS Microsoft Windows 7 Professional (64-bit)
  • PostgreSQL 9.4.1 (x64)
  • PostGIS 2.1.5 (x64)
  • QGIS 2.6.1 (Brighton)
  • OS Translator II 1.0
  • Python 2.7.9 (win32)
  • lxml 3.2.3 (win32)
  • Loader Master (067a511313, 20th February 2014)

2 Operating system and source gml.gz files located on the SSD and default PostgreSQL tablespace stored on secondary 2TB HDD.

PostgreSQL Configuration

The following changes were made to the default PostgreSQL configuration:

  • shared_buffers 512MB
  • work_mem 16MB
  • maintenance_work_mem 128MB / 1024MB3
  • checkpoint_segments 6
  • random_page_cost 2.0
  • fsync off

3 maintenance_work_mem was set to 1024MB for the national load of MasterMap Topography layer only.

Turning fsync off is dangerous and can lead to data loss in the event of an unexpected power outage. Always switch fsync back on after loading and never use this option on a database containing critical data.

New stable release of GRASS GIS 7.0.0!

The GRASS GIS Development team has announced the release of the new major version GRASS GIS 7.0.0. This version provides many new functionalities including spatio-temporal database support, image segmentation, estimation of evapotranspiration and emissivity from satellite imagery, automatic line vertex densification during reprojection, more LIDAR support and a strongly improved graphical user interface experience. GRASS GIS 7.0.0 also offers significantly improved performance for many raster and vector modules: “Many processes that would take hours now take less than a minute, even on my small laptop!” explains Markus Neteler, the coordinator of the development team composed of academics and GIS professionals from around the world. The software is available for Linux, MS-Windows, Mac OSX and other operating systems.

Detailed announcement and software download:

The Geographic Resources Analysis Support System (, commonly referred to as GRASS GIS, is an open source Geographic Information System providing powerful raster, vector and geospatial processing capabilities in a single integrated software suite. GRASS GIS includes tools for spatial modeling, visualization of raster and vector data, management and analysis of geospatial data, and the processing of satellite and aerial imagery. It also provides the capability to produce sophisticated presentation graphics and hardcopy maps. GRASS GIS has been translated into about twenty languages and supports a huge array of data formats. It can be used either as a stand-alone application or as backend for other software packages such as QGIS and R geostatistics. It is distributed freely under the terms of the GNU General Public License (GPL). GRASS GIS is a founding member of the Open Source Geospatial Foundation (OSGeo).

The post New stable release of GRASS GIS 7.0.0! appeared first on GFOSS Blog | GRASS GIS Courses.

Plugin Builder 2.8

The Update

Plugin Builder 2.8 is now available. This is a minor update that adds:

  • Suggestion for setting up an issue tracker and creating a code repository
  • Suggestion for a home page
  • Tag selection from a list of current tags
  • Documentation update, including information about using pb_tool to compile, deploy, and package your plugin
  • New URLs for Plugin Builder’s home page and bug tracking

Optional is now Recommended

In previous versions the following items were “Optional” when creating a new plugin:

  • Bug tracker
  • Home page
  • Repository
  • Tags

We’ve changed those from “Optional” to “Recommended” because they are important for the success and longevity of your plugin(s). Setting up a code repository on GitHub automatically gives you issue tracking and the ability for others to collaborate with fixes and enhancements through pull requests.

Using GitHub also gives you the ability to setup a home page right from your repository using GitHub pages.

Adding one or more tags to your plugin helps people find them easier when browsing the QGIS Plugins website.

Getting It

You can install Plugin Builder 2.8 from the Plugins -> Manage and Install Plugins… menu. Version 2.8 works on QGIS versions 2.0 and up.

Towering QGIS 2.8 Release

The new QGIS 2.8 release (codename: Wien) is out tomorrow!

Lutra’s very own QGIS core developer Martin Dobiaš has been working hard with others on bringing you new stuff. So, what exciting new features are provided by this jauntily-angled new release? There are plenty of eagerly-anticipated additions – both big new features, and under-the-hood improvements – as well as bugfixes.

Read on for a look at some of the new features in more detail…

Multiple Stylings

Have you ever found yourself duplicating layers just so you could display the same data but with additional styles? Those days are now over.

You can now define multiple styles for a single layer, and easily switch between them in the layer view or layer properties dialog.

Multiple styles in the legend

Multiple styles in the layer dialog

Just so our webmapping colleagues don’t feel left out this new behaviour is extended to the WMS server too. The available multiple styles are advertised in GetCapabilities and can be used in other requests, such as GetMap.

And of course it all works in the map composer too – which means more maps with the same layers displayed in different styles.

Multiple styles in the map composer

Work carried out in cooperation with Gis3W for Regione Toscana.

Making It Snappy

Snapping is made simpler with the addition of new modes for snapping, so you can now:

  • Snap to current layer
  • Snap to all layers
  • Perform advanced per-layer snapping (previously the only mode)

New snapping modes

There’s also less confusion with snapping tolerances being to map units or layer units, so those anticipated 1 metre tolerances don’t become 1 degree tolerances without you knowing.

Snapping is not only more straightforward – it’s now much faster too thanks to using an index of geometries built when first needed. Because everybody loves faster, right?

For our developer colleagues there is an easy to use API which – amongst other things – adds fast point in polygon queries.

Funded by Ville de Vevey, SITNyon and QGIS Usergroup Switzerland.

More info here.

Simplify Simplified

QGIS has had a simplify tool for a while, but now it’s been significantly improved with lots of tasty new ingredients.

Improved simplify tool

Simplify tool tolerances used to be different for every feature – but not any more, and users can specify exact tolerances – which can be in map units or layer units.

Also new is on-the-fly reprojection support, tolerance settings are now persistent between sessions, dragging a rectangle instead of just clicking to simplify multiple features, support for multi-part features, and statistics about reduction of the number of vertices – because if you’re simplifying, it’s nice to know by how much! Oh yes, and faster too!

Work carried out in cooperation with Kartoza.

One Legend To Rule Them All

The display of rules in the legend for rule-based rendering has continued its evolution in features from QGIS 2.4:

QGIS 2.4: Good – a flat list of rules, but you can’t see the nesting.

Rules in 2.4

QGIS 2.6: Better – shown as a pseudo-tree with checkboxes.

Rules in 2.6

QGIS 2.8: Best – great for power-users who use complex styling rules to give their maps that extra zing.

Rules in 2.8

Funded by SIGE.

Long-Term Love

QGIS is also the first Long-Term Release (LTR) version – starting with 2.8 every third release is a long-term-release – maintained until the next long-term-release occurs.

Even if you’re a new-feature-junkie, you’ll appreciate the commitment by the project to both innovation and stability, and this of course underlines the burgeoning success of QGIS in enterprise environments.

So, start your engines, and get ready to download!

Making It Happen

While you’re still reeling from finding out about some of the new goodies that QGIS 2.8 brings (and check the official QGIS changelog for more!), I’ll remind you that all this cool stuff somehow needed to be paid for.

Thanks go to the organisations and individuals that sponsor or contribute to the QGIS project, and those that fund development of specific features. They make the software better for everyone, and you or your organisation could become one of them!

We at Lutra Consulting are Bronze level sponsors of the QGIS project, and use our development experience to contribute code and develop plugins for QGIS.

We tackle this in several ways, including direct approaches from clients to fund custom development, and crowdfunding campaigns. So, if you’re interested in some functionality that isn’t yet there – get in touch!

Calcular coordenadas do centroide de polígonos | Calculate polygon centroid’s coordinates

Tive necessidade de, numa camada de polígonos, adicionar colunas à tabela de atributos com as coordenadas dos centroides das geometria. Cheguei às seguintes expressões para calcular as coordenadas X e Y, respectivamente:

I had the need to add columns with the coordinates of polygons centroids. I came up with the following expressions to calculate X e Y, respectively:


A expressão parece bastante banal, mas ainda demorei a perceber que, não existindo funções x(geometry) e y(geometry), podia usar as funções xmin() e ymin() para obter as coordenadas dos centroides dos polígonos. Uma vez que esta não foi a primeira vez que precisei de usar estas expressões, fica agora o registo para não me voltar a esquecer.

The expression seems quite simple, but it toke me some time before I realize that, not having a x(geometry) and y(geometry) functions, I could use the xmin() and ymin() to get the coordinates of the polygons centroids. Since this wasn’t the first time I had to use this expressions, this post will work as a reminder for the future.

QGIS course at AfQUA

Kartoza has just wrapped up a three-day Introduction to QGIS course that we gave pro bono at The African Quaternary: Environments, Ecology and Humans conference in Cape Town (AfQUA2015). Thank you to Kelly Kirsten from the local organising committee at the University of Cape Town for inviting us. Admire Nyakudya presented to about fifteen conference delegates from around the world. Attendees ran QGIS 2.6.1 on their own notebooks on the operating system of their choice. Some already use QGIS, some were experiencing QGIS for the first time and some some wanted to compare it with ArcGIS. The course content was guided largely by the QGIS training manual but as we usually do, adapted for the requirements, interests and pace of the class.


Kartoza QGIS class at AfQUA 2015

Admire presenting QGIS workshop at AfQUA

Happy 9th Birthday, OSGeo!

Press release by Jeff McKenna, OSGeo Foundation President

9 years ago today was the first ever meeting of the OSGeo foundation, in Chicago U.S.A. (initial press release). Thanks to those passionately involved back then, and the thousands contributing since, now our community has expanded and has reached many countries all over world. Congratulations to everyone for continuing to share the passion for Open Source geospatial.

Here is a glimpse at some of the exciting events happening around the world this year:

The post Happy 9th Birthday, OSGeo! appeared first on GFOSS Blog | GRASS GIS Courses.

A star is born, QGIS mobile is now QField

It is with great pleasure that we want to announce the new name for what was briefly known as QGIS mobile. Please welcome QField for QGIS™! QField is an Open Source field data capture and management app fully compatible with QGIS™ which allows you to take your QGIS projects out of the office for effective field work while maintaining QGIS' styling and edit widgets QField for great preparation time. QField will be released for free on the Playstore with the possibility of donating to the project via paypal (preferred) or by buying the QField for QGIS Karma edition app.

Publishing interactive web maps using QGIS

We all know that QGIS is great for designing maps but did you know that QGIS is also great for interactive web maps? It is! Just check out qgis2leaf and qgis2threejs.

To give these two plugins a test run and learn some responsive web design, I developed a small concept page presenting cycle routes in 3D.

Screenshot 2015-01-31 22.20.15

Qgis2leaf makes it possible to generate Leaflet maps from QGIS layers. It provides access to different background maps and it’s easy to replace them in the final HTML file in case you need something more exotic. I also added another layer with custom popups with images but that was done manually.

Daten CC-BY-3.0: Land Kärnten -

The web maps use data CC-BY-3.0: Land Kärnten –

Qgis2threejs on the other hand creates 3D visualizations based on three.js which uses WebGL. (If you follow my blog you might remember a post a while back which showcased Qgis2threejs rendering OSM buildings.)

This is a great way to explore elevation data. I also think that the labeling capabilities add an interesting touch. Controlling the 3D environment takes some getting used to, but if you can handle Google Earth in your browser, this is no different.

Image of Heiligenblut by Angie (Self-photographed) (GFDL ( or CC BY 3.0 (, via Wikimedia Commons

Image of Heiligenblut by Angie (Self-photographed) (GFDL ( or CC BY 3.0 (, via Wikimedia Commons

QGIS Layer Tree API (Part 3)

In the two previous blog posts we have learned how to query a layer tree and how to modify it. All these new APIs are available since QGIS 2.4 release. Today we will look into how to make layer trees available in GUI and connect them with a map canvas.

Model/View Overview

As we have seen earlier, a layer tree is a usual hierarchical data structure composed from nodes of two types – layers and groups. They do not provide any GUI functionality as they live in the QGIS core library. In order to visualize a layer tree, we will use Model/View approach from Qt framework. Readers not familiar with those concepts are recommended to read the Qt Model/View overview first.

Layer tree model/view

There is QgsLayerTreeModel class (derived from QAbstractItemModel) which as you may have guessed provides a model to access a layer tree. Instance of this class may be used in any QTreeView class, however it is recommended to use it together with QgsLayerTreeView because of the extra convenience functionality offerred by the custom view class.

Here is an example how to create another view of current project’s layer tree (try that in QGIS Python console):

from qgis.gui import *

root = QgsProject.instance().layerTreeRoot()
model = QgsLayerTreeModel(root)
view = QgsLayerTreeView()

Any changes that happen to the layer tree structure are automatically monitored by the model/view classes. After running the example above, try changing a layer’s name or add/remove/reorder some layers – all those actions will be immediately visible in all views.

As you can see, the layer tree view is just one way how to visualize the underlying layer tree – in the future it may be possible to have different ways to show the layer tree, for example using Qt’s QML framework (with all sorts of animated transitions known from mobile apps).

Plugin developers can access the layer tree view in the main window of QGIS through the following interface call:

view = iface.layerTreeView()

More About the Model

The model is meant to be flexible and it is possible to use it in various contexts. For example, by default the model also provides legend for the layers in the tree. This however may not be wanted in some cases. Similarly, sometimes the layer tree should be read-only while in other context it is desired that the user can reorder layers or change their names. These preferences can be passed to the model with flags:

model = QgsLayerTreeModel(root)

The setFlag() method has optional second parameter “enabled” (True by default). Flags can be also set all at once with setFlags() method which expects a combination of flags joined by binary OR operator. There are also flags() and testFlag() methods to query the current flags.

The QgsLayerTreeModel class also provides routines for conversion between QgsLayerTreeNode instances and corresponding QModelIndex objects used by Qt Model/View framework – index2node() and node2index() may come handy especially when working with views.

There is also some functionality related to legend display – it has been greatly extended in QGIS 2.6 release and we will try to cover that in a future blog post.

More About the View

As mentioned earlier, it is possible to use any QTreeView instance in combination with QgsLayerTreeModel to show the layer tree, but it is highly recommended to use QgsLayerTreeView class (a subclass of QTreeView) because of the additional functionality it provides (and more may be added in the future):

  • Easier handling of selection. Normally one needs to work with selection through view’s selection model. The QgsLayerTreeView class adds higher level methods that operate with QgsLayerTreeNode objects like currentNode() or with QgsMapLayer objects like currentLayer().

    def onChange(layer):
      QMessageBox.information(None, "Change", "Current Layer: "+str(layer))
    # connect to the signal
    # change selection to the top-most layer (onChange will be also called)
    view.setCurrentLayer( iface.mapCanvas().layers()[0] )
  • Display of context menu. It is possible to assign a menu provider to the view (subclass of QgsLayerTreeViewMenuProvider) – its createContextMenu() implementation will return a QMenu object with custom actions whenever user right-clicks in the view. Additionally, there is a factory class QgsLayerTreeViewDefaultActions that can create commonly use actions for use in the menu, such as “Add Group”, “Remove” or “Zoom to Layer”. The following example shows how to create a provider with one action that shows the current layer’s extent:

    class MyMenuProvider(QgsLayerTreeViewMenuProvider):
      def __init__(self, view):
        self.view = view
      def createContextMenu(self):
        if not self.view.currentLayer():
          return None
        m = QMenu()
        m.addAction("Show Extent", self.showExtent)
        return m
      def showExtent(self):
        r = self.view.currentLayer().extent()
        QMessageBox.information(None, "Extent", r.toString())
    provider = MyMenuProvider(view)

Interaction with Canvas

The layer tree classes and map canvas class are separate components that are not dependent on each other. This is a good thing and a great step forward, because until QGIS 2.2 there was big internal monolithic QgsLegend view class that handled everything and it was directly connected to map canvas and various other components, making it impossible to reuse it elsewhere. With the new layer tree API this has been solved, now it is possible use map canvas without an associated layer tree view or vice versa – to use a layer tree view without map canvas. It is even possible to get creative and use one layer tree with several map canvas instances at once.

Layer tree and map canvas can be connected via QgsLayerTreeMapCanvasBridge class. It listens to signals from the given layer tree hierarchy and updates canvas accordingly. Let’s see how we could create a new map canvas that would show the same layers as the main canvas does:

canvas = QgsMapCanvas()
root = QgsProject.instance().layerTreeRoot()
bridge = QgsLayerTreeMapCanvasBridge(root, canvas)

That’s it! We have tied the new canvas with project’s layer tree. So any actions you do in the layer tree view (for example, add or remove layers, enable or disable layers) are automatically passed to the new canvas. And of course this does not work just with project’s layer tree – you could use any custom layer tree in your layer tree model/view or canvas.

The bridge class has advanced functionality worth mentioning. By default the ordering of layers in canvas is according to the order in the layer tree (with first layer in the tree being at the top), though there are API methods to override the default order.

For convenience, the bridge by default also configures some settings of the canvas (this can be disabled if necessary):

  • enable on-the-fly reprojections if layers have different coordinate reference system (CRS)
  • setup destination CRS and map units when first layers are added
  • zoom to full extent when first layers are added


I hope you have enjoyed the three blog posts introducing QGIS layer tree API. They should cover everything you need to know in order to start using the new functionality. In a future post we will have a look at the new legend API that nicely complements the layer tree API – stay tuned!

How to load a QGIS project in python

Today in a project we are working on we wanted to load a QGIS project. It takes  surprisingly few lines of code to make a small standalone application that loads a project and then shows it as a map in a window like this:

QGIS project in a standalone app


Here is the code I wrote to produce this:

The main bit of magic is the QgsLayerTreeMapCanvasBridge class which will convert your project into a layer tree so that the layers appear in the canvas. If you ever need to make a standalone python application with a nice map in it, consider using the QGIS API to do it!

New addition

Stace and I would like to welcome Matilda Anne Woodrow, born 5/1/15 at 10:36am.


She is a nice way to start 2015.

After the pretty crappy year that was 2014 it was finally nice to see Matilda in the flesh. The relief of seeing her alive and well is hard to put in words after losing Ellie in 2013.

People always ask about the lack of sleep, but it feels like we have more energy now then we did before. The emotional and physical toll that the pregancy took on our family had pretty much run us into the ground and it felt like it was never ending.

The toll of the pregancy had lead me to massive lack of motivation towards QGIS and pretty much everything else in life, which isn't healthy when you have a family to look after. Pro Tip: Get help if you find yourself in this spot, it be hard to recover if you go over the edge.

Anyway. Here is to a new year. A better year.

Function editor for QGIS expressions

A new feature for QGIS 2.8 is a function editor for expressions. Being able to define your own custom functions has be possible for a while now, over a year, I even have a plugin (Expressions+) that adds some extra ones, however it wasn't easy for new users and required you to create files that lived on python path while also editing the file for QGIS so that functions got registed at start up. Way too much effort for my liking.

This feature is now exposed via the expression builder on the Function Editor tab. The function editor will create new Python files in qgis2\python\expressions and will auto load all functions defined when starting QGIS. I remember Sean Gillies saying that Python support in a field calculator should be a gateway to full Python programming, can't get any more Python then full Python modules.

The best way to show this feature is a quick video so here it is

The play button in the editor will run the current editor file in the QGIS session and register any functions it finds, it will also save the file in the expressions folder.

You can make a new file by pressing the new file button which will add the basic function template, changing the name in the combobox and hitting save will save the file.

The function editor allows you have to define reuseable functions for your QGIS. If you want to share a function you simply share the .py file from the expressions folder and give it to another user. In future versions of QGIS we might have a way to download other users functions.

Auto expanding values

You can also use the args="auto" keyword in place of the number of args which will let QGIS work it out and expand the arguments for you.

Here is an example

@qgsfunction(args="auto", group='Custom')
def myfunc(value1, value2 feature, parent):

and can be used like this:

myfunc('test1', 'test2')

QGIS will workout how many arguments your function takes based on what you have defined. Note: The last arguments should always be feature, parent, these are not included in the count.

Raising errors

If you need to report a error from a function simply use the raise method like normal in QGIS and raise an exception.

@qgsfunction(args="auto", group='Custom')
def myfunc(value1, value2 feature, parent):
    raise Expection("Hahah Nope!")

The function wrapper will catch the exception and raise it though the expression engine.

A couple of things to note

  • New functions are only saved in the expressions folder and not in the project file. If you have a project that uses one of your custom functions you will need to also share the .py file in the expressions folder.
  • The editor doesn't unregister any functions. If you define a function called test, hit play, change the name to test_2, hit play, both functions will exist until you reload QGIS.

  • Page 1 of 73 ( 1442 posts )
  • >>

Back to Top