7

In QGIS, I use the python console to generate image files through the composer. In particular, I am creating a map with a legend. The legend is too big. It occupies about 1/8 of the image. I would like to make the legend smaller.

The code that adds the legend to the composition is:

c = QgsComposition(mapRenderer)
c.setPlotStyle(QgsComposition.Print)
cleg = QgsComposerLegend(c)
cleg.model().setLayerSet(mapRenderer.layerSet())
cleg.setItemPosition(0,45)
c.addItem(cleg)

A legend is created, but it is too big. In order to make it smaller, I have been reading the documentation of the QgsComposerLegend and QgsComposerItem classes, with no positive results. In particular, I have been trying to change the legend size by typing

cleg.setItemPosition(0,45,3,10)

but the size does not change.

I think I might have to make the font smaller first. If that is the case, I should use setStyleFont, which depends on a QgsComposerLegendStyle object which I don't know how to retrieve (I have tried to use the rstyle function, but I don't know how to use it).

In summary, could you please provide an example on how to:

  1. Make the legend smaller
  2. Make the legend font smaller?

Thank you!

  • In the composer window there is an option to word wrap on a particular character sequence. I am afraid I am ignorant of the Python API (todo list) but you might see if the newline escape sequence '\n' could be inserted programmatically into your legend strings. Or use a mesh of the composer and scripting to achieve a smaller width. – RomaH Mar 25 '14 at 22:33
3

As you guessed it's impossible to make the legend smaller then its contents. So, to change the legend font size, use something like:

newFont = QFont("Comic Sans MS", 6)
cleg.setStyleFont(QgsComposerLegendStyle.Title, newFont)
cleg.setStyleFont(QgsComposerLegendStyle.Subgroup, newFont)
cleg.setStyleFont(QgsComposerLegendStyle.SymbolLabel, newFont)

(depending on which component of the legend text you want to change). You may also want to adjust the symbol spacing, which can be done using code like:

cleg.rstyle(QgsComposerLegendStyle.Symbol).setMargin(QgsComposerLegendStyle.Top, 0)

Lastly, to adjust the symbol box size:

cleg.setSymbolHeight(2)
cleg.adjustBoxSize()

Using those three adjustments you should be able to reduce the size of your legend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.