I would like to add a scale bar to my composition using the python console and then export it to a raster image.
I am following the MapRendering tutorial with the "output using map composer " approach
however,the Scale Bar item example do not have many features.
I would like
- a scale bar with 2 ticks, one at the beginning, one at the end
- units in km
- eventually round it to the nearest km
- place it on the upper right of my figure.
- set a transparent background
Just like in the desktop QGIS version.
What are the options ?
So far I have found
item = QgsComposerScaleBar(c)
item.setStyle("Line Ticks Up") # optionally modify the style
item.setComposerMap(composerMap)
c.addItem(item)
Will the scale bar be "at scale" ?
Thank you for your help
I cannnot find anything from that page
ScalBar class
Best Answer
Your scale bar's scale will be relative to an existing composer map item that is assigned to it:
QgsComposerScaleBar.setComposerMap(mymap_item_obj_here)
. So you will need to create the composer map item first, so it's scale can be referenced by the scale bar.I found almost all the necessary functions to create the custom scale bar you want on that page.
Once the composer map reference is set, all other QgsComposerScaleBar attributes can be set using the class's public member functions, or those functions inherited by the scale bar's base class, QgsComposerItem, like setItemPosition().
Base class inheritance diagram
I guessing here, but for setting the opacity for the background to zero, you will probably want to set the QBrush used in QgsComposerScaleBar.setBrush(QBrush) to have a QColor with an alpha of 0.
EDIT (response to your further questions/clarifications):
I was incorrect in assuming the QBrush in question belonged to the encompassing frame. The brush is actually the color for the scale bar's font. The frame and its background are part of the inherited QgsComposerItem class. To effectively work with its methods of a similar name (setBrush() in this example), you need to access it via Python's super() function (using your ScaleBar object here):
This will reference the super class of the object, and set it to transparent black, much like setting parameters in the General options section for a composer item.
You need to create a QFont, set its size, then set the scale bar's font to it. You can begin by pulling in the QFont from the scale bar.