For work I always have to create a table with my name, project name, date etc. into my map layouts. I also need to include the scale like "1:150000" in that table.

So far I am solving that by including an html table with the html box function of the print composer. Is there a way to automatically include the right scale? So far I only managed to automatically include the date by using a little javascript. Maybe something similar is also possible for the scale?

  • 1
    I'm looking for the same thing but for the date I could recommend another 'native' way: [%day($now)||'.'||month($now)||'.'||Year($now)%] This expression will be processed by QGIS. – meles Dec 16 '15 at 12:36

Tested with QGIS 3.6.1

As mentioned in the documentation, you can create a label and insert this code to get the current scale for the map with the item name Map 0:

map_get( item_variables('Map 0'), 'map_scale')

You can register expression function to get your map scale. For example:

from qgis.utils import iface 

@qgsfunction(args='auto', group='Custom')
def get_composer_map_scale(comp_window_title, feature, parent):
    composer_views = iface.activeComposers()
    my_composition = None
    for view in composer_views:
        if view.window().windowTitle() == comp_window_title:
            my_composition = view.composition()
    if my_composition is not None:
        # adjust map id below if you have more maps in the composer
        comp_map = my_composition.getComposerMapById(0)
        scale = '{:.0f}'.format(round(comp_map.scale(), 0))
        return scale
        return 'Unknown'

And use it in your HTML box or label:

Scale 1:[%get_composer_map_scale( 'Composer 1' )%]

where 'Composer 1' is your composer title.

  • 1
    I'm assuming that the new QGIS 3 API breaks this function, is that correct? – HeyOverThere Oct 11 '18 at 5:13
  • This is an outdated answer (only works for qgis 2). – Comrade Che Aug 22 '19 at 11:51

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.