“In this module we explore how expressions can be used in map composer”
Expressions are just simple formulas that QGIS will calculate on the fly. Expressions in QGIS provide a powerful way to include dynamic content in your layers, in an analysis, and various other places. They can also be used to make your map composers change their appearance dynamically. In this module, we will explore the expression system in QGIS Composer to provide some examples of how they may be used to define labels, colours and so on. If you have not already completed our worksheet on basic expression use, you should probably do that first since we will assume that you already know how to use expressions. There are two main ways in which expressions can be used:
Goal: To learn how to use expressions in QGIS Composer labels
red
. Normal text [% expression % ] more normal text
You will need to use this approach for labels which combine standard text and the contents of expressions (such as in the last requirement in the table below). Note that the last requirement only provides hints, you need to work out the complete syntax.
Name | Expectation |
---|---|
Expression for feature count for wards layer |
[% layer_property('Wards2011','feature_count')%] |
Expression for operating system |
[%upper( @qgis_os_name ) %] |
Expression for QGIS Version |
See variables qgis_release_name and qgis_version |
The real value of expressions in your map composition is that these expressions are dynamic. Taking our exercise example above, you may have noticed that your operating system box contains different text to the image provided above. That is because when the composer layout draws itself, it checks to see what the current operating system is and then displays that in the label. Similarly, the feature count label will update itself automatically should you add or remove a feature from the wards layer. Try removing one of the wards now and then commit the changes to see how the label updates itself.
Using variables with composer expressions provides a very powerful way to dynamically change the appearance of your map. For example, you can create a variable (in the QGIS Setting dialogue) for your project colour (e.g. project_colour
set to #BB7364
) and then use that variable for data-driven properties for accent colours in your report. By the way, in the specific example given in the last sentence, you might be unfamiliar with the way that colours are described e.g. #BB7364
. This is a hexadecimal colour notation, and you can easily obtain these hexadecimal colours from the colour picker widgets in QGIS or from a website like https://htmlcolorcodes.com.
When should you use expressions in composer?:
What would the label produced from this expression look like? Gotta have a slice of [% pi() %]:
Download the sample data for the lesson.