I added a QgsComposerScaleBar to a QgsComposition.

I wish to have segment rounded to the nearest km but I don't know how to achieve this.


After browsing the documentation a little more, here is how I'd do it :

# Create the scale bar and position it
x, y = 217, 192
w, h = 35, 18
scalebar = QgsComposerScaleBar(composition)
scalebar.setItemPosition(x, y, w, h)
scalebar.setStyle('Single Box')

# The default map unit is "meters", but you wanted the scalebar in "km"
# The map has to have an appropriate coordinate system, though.
# WGS84 won't work, for instance, as it uses angular units.

# Find out the total size of the scalebar, in map units (m)
scalebar_size = map.extent().width() / map.rect().width() * w

# Convert it to km
scalebar_size /= 1000.

# Find the size of a segment
number_of_segments = 2
segment_size = scalebar_size / number_of_segments

# Round it to the nearest km, with a minimum of 1 km
# Note that for smaller maps this will create a huge scalebar!
segment_size = max(1, round(segment_size))

# Divide the scalebar

# Finally, add the scalebar to the composition

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.