8

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
  • 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, 2015 at 12:36

2 Answers 2

6

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')
3

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()
            break
    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
    else:
        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.

2
  • 1
    I'm assuming that the new QGIS 3 API breaks this function, is that correct? Oct 11, 2018 at 5:13
  • This is an outdated answer (only works for qgis 2). Aug 22, 2019 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.