The QgsComposition
object allows you to place arbitrary text anywhere in the composition. In this recipe, we'll demonstrate how to add a label to a map composition.
You will need to download the following zipped shapefile and extract it to your qgis_data
directory, to a subdirectory named hancock
:
https://geospatialpython.googlecode.com/svn/hancock.zip
In addition to the shapefile, you will also need the MapComposer
class. This class encapsulates the boilerplate composer code in a reusable way to make adding other elements easier. You can download it from https://geospatialpython.googlecode.com/svn/MapComposer.py.
This file must be accessible from the QGIS Python console by ensuring that it is in the Python path directory. Place the file in the .qgis2/python
directory within your home directory.
To add a label to a composition, we'll first build the map composition, create a label, and then save the composition as an image. To do this, we need to perform the following steps:
MapComposer
class:from PyQt4.QtGui import * from PyQt4.QtCore import * import MapComposer
lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/hancock/hancock.shp", "Hancock", "ogr")
reg = QgsMapLayerRegistry.instance() reg.addMapLayer(lyr)
mr = iface.mapCanvas().mapRenderer()
MapComposer
object, passing in the map layer registry and the map renderer:qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
qc.label = QgsComposerLabel(qc.c)
qc.label.setText("Hancock County")
qc.label.adjustSizeToText()
qc.label.setFrameEnabled(True)
qc.label.setItemPosition(qc.x,qc.y-10)
qc.c.addItem(qc.label)
qc.output("/Users/joellawhead/qgis_data/map.jpg", "jpg")
In this case, we created a very simple label based on defaults. However, labels can be customized to change the font, size, color, and style for print-quality compositions. Also, note that the x,y values used to place items in a composition start in the upper-left corner of the page. As you move an item down the page, the y value increases.