I'm loading a layout template to a .qgs project and would like to set up the scale bar so that it has a round numeric scale (e.g. 1:5'000, or 1:25'000 but not 1:12'500). How do I do that?
Here is my piece of code:
import os
import processing
from qgis.core import *
from qgis.gui import *
import qgis.utils
from qgis.PyQt import QtGui
from qgis.PyQt.QtXml import QDomDocument
project = QgsProject.instance()
project.setCrs( QgsCoordinateReferenceSystem(2056, QgsCoordinateReferenceSystem.EpsgCrsId) )
project.setFileName(qgis_project_name)
project.write()
# load layout template
composition = QgsPrintLayout(project)
document = QDomDocument()
template_file = open('C:\\my_QGIS\\my_qgis_projects\\ramms_map\\RAMMS_Karte.qpt')
template_content = template_file.read()
template_file.close()
document.setContent(template_content)
composition.loadFromTemplate(document, QgsReadWriteContext())
project.layoutManager().addLayout(composition)
layout = project.layoutManager().layoutByName("RAMMS_Karte_layout_de")
# access the items contained in the layout
sel = layout.itemById("scale") # that's the id of the scalebar item
sel.??? --> here set the numeric number 1: xxxx
# my scalebar is connected to a map ("map1")
EDIT:
# here is the correct piece of code missing
layout = project.layoutManager().layoutByName("RAMMS_Karte_layout_de")
map1 = layout.itemById("map1")
scale_nr = map1.scale() # takes the scale of map1
if (scale_nr % 1000.0 == 0.0) == False: # if not divisible by 1000, it rounds the scale value to the next 1000
scale_nr = int(round(scale_nr, -3))
map1.setScale(scale_nr) # sets the new scale