6

I want to get the scale of my Layout that I created. For this I thought of using the QgsLayoutItemMap class. The problem is that the scale method in QgsLayoutItemMap always returns 0.0. I know I am doing something wrong but I don't know what. Here is the code I am using:

projectInstance = QgsProject.instance()
projectLayoutManager = projectInstance.layoutManager()
item = projectLayoutManager.layoutByName("asd")
tail = QgsLayoutItemMap(item)
tail.scale()
4
  • you want to use the scale inside pyqgis or do you want to show the scale as a numeric value in a label in your print composer?
    – LaughU
    Commented Jan 22, 2018 at 14:37
  • I want to show the scale as a numeric value in a label.
    – Blinxen
    Commented Jan 22, 2018 at 15:10
  • Your questio is for qgis2, mine is for qgis3. In qgis3 there is no such thing as composer, it's called layout now.
    – Blinxen
    Commented Jan 22, 2018 at 15:29
  • ups your right my bad!
    – LaughU
    Commented Jan 22, 2018 at 15:30

2 Answers 2

8

I solved the mystery about the scale. First I have to search for the layout I want to use:

projectInstance = QgsProject.instance()
projectLayoutManager = projectInstance.layoutManager()
projectLayoutManager.layouts()

With this we get all layouts that we have. Then we chose which one we want to use.

layout = projectLayoutManager.layouts()[0]   #chose layout

The method referenceMap in QgsLayout is what we need now. Let's say our layout is a QgsPrintLayout. Because QgsPrintLayout inherits all methods from QgsLayout, we can use the referenceMap method and that will help us use the scale method in QgsLayoutItemMap. And then we can use our scale method to get our scale. Here is the rest of the code:

referencemap = layout.referenceMap()
referencemap.scale()
7

Your solution is using Python. I'm gonna give how to get the scale using a QGIS Expresion only:

First, set a ITEM ID on your map item, in the tab properties: map item ID

Then, in your label, you the expression:

 [% map_get(item_variables( 'map1' ), 'map_scale') %]

This is will output the scale of the map called 'map1'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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