[QGIS-Developer] PyQgis: Composer and legends scripting

Jorge Tornero jtorlistas at gmail.com
Fri Nov 22 04:33:42 PST 2019


Hello all,
I'm trying to make a script with python (standalone, not in qgis console or
whatever) for exporting composer maps to an image.

The idea is to have a template of a map and just change some layers, the
title, etc., depending on the data I want to show. For instance, I can
have a base map with a bathymetry layer, a geography (land) layer and then
produce several maps with, say the abundance of a particular species of
fish.
So far I'm able to:

1) Import qgis and create a QgsApplication

from qgis.core import *
QgsApplication.setPrefixPath("",
True)qgs=QgsApplication([],False)qgs.initQgis()

2) Create and load a project from a file

pro=QgsProject()pro.read('./miproject.qgs')

3) Access to its layout manager and thus to one particular layout
pro=QgsProject()pro.read('./miproyecto.qgs')layoutManager=pro.layoutManager()
layout=layoutManager.layoutByName('MYLAYOUT')

4) And then export that layout to a file:

exporter=QgsLayoutExporter(layout)
exporter.exportToImage('mymap.png',exporter.ImageExportSettings())


But I'm having big trouble trying to manipulate the legend itself.
I can get the legend with (I omit the listing of layout items to get the
index of the legend):

legend=layout.items()[2]

But how could I access to the legend items and be able to modify them?

So far I know that I can access to the legend model through legend.model(),
and then with say tree=lengend.model().rootGroup() I guess I get the legend
tree. In fact I can begin to hear some music with dump() and I have had
success up to some extent and even changing some text in the legend items,
but it looks like the way I made it is far from being fair. For instance,
for changin one particular name inside the legend I've made:

tree.children()[0].children()[0].setName('New Name')


But I can't figure out how to manipulate that tree for changing the legend
matching the information layer corresponding to each particular map. It
looks like it has something to do with accessing to the XML of the tree and
manipulating, but my efforts with writeXML() and trying to get something
from it led to nonsense.

So I will appreciate so much some clues about how to access and modify the
legend of a print layout.

The last intention of this is to use thise scrips to include output from
QGIS maps directly into RMarkdown documents. I consider that producinq maps
with QGIS is by far more versatile than with R and I've made some test and
it would work like a charm.

Thank you very much for your help, all the best

Jorge Tornero
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20191122/12514cda/attachment.html>


More information about the QGIS-Developer mailing list