Aller au contenu | Aller au menu | Aller à la recherche

Need to stick to some scales in QGIS ?

My colleague, Michaël, would like to be able in QGIS to force the canvas scales to some predefined ones. Since we now have project scales (and QGIS pre-defined scales) in the scale selector, we could use them, and add a simple checkbox near the combobox Stick to predefined scales.

The aim is to force the canvas to render only at these scales. For example, if a QGIS user uses the rectangle zoom tool, and he should go to 1/56003, he would instead land on 1/50000, the closest pre-defined scale.

He made a little python script as a proof of concept to illustrate it:

# -*- coding: utf-8 -*-

# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *

class forcedScale():
    # pre-defined scales
    # has to be read from project properties
    predefinedScales = [
    # mapCanvas
    mc = None
    def init( self ):
        Initialize class instance
        mc = iface.mapCanvas() = mc

   def setScale( self, scale ):
       targetScale = min(
           key=lambda x:abs(x-scale)
       ) targetScale )

In this script, he hard coded the scales, but obviously we should get them from the project properties.

Run this script in the QGIS Python console and initialize with fs = forcedScale() to stick to scales.

A discussion has been opened in QGIS-Dev mailing list :


1. Le vendredi 17 avril 2015, 14:31 par kimaidou

Improve version here:


* "replayed" variable to avoid probable infinite loop
* you can now initialize the method with a python list of scales you want to force canvas to, for example:

fs = forcedScale( [25000, 50000, 100000 ] )