2

I wish to add a keyboard shortcut to set a Map View to a specific scale. (Qgis3.3)
So that i can link that shortcut to a button on my digitizer tablet.

the python code should be something like

  iface.activeLayer().renderer().setReferenceScale(1000)
or
  iface.mapCanvas().zoomScale(1000)

How can I link this to a keyboard shortcut?

I don't see how I can add a custom action in Settings, Keyboard Settings
google search and even newfangled AI suggest that this should be possible?

see ZZZ code ai

1 Answer 1

3

You can leverage the keyPressed signal emitted by the QGIS GUI. Here I bind the functionality to the iface.mapCanvas() specifically, so that it must have focus for the shortcut to work. However, you could put it on a higher level widget such as the main window.

This can be run in the Python console. You can of course alter (or remove) the modifier and change the specific key to be pressed.

Zoom to scale 1000 with Ctrl + Y:
def zoom_to_scale(event, scale):
    # check if Ctrl is held
    if event.modifiers() & Qt.ControlModifier:
        # check if Y is pressed
        if event.key() == Qt.Key_Y:
            iface.mapCanvas().zoomScale(scale)
                    
con = iface.mapCanvas().keyPressed.connect(lambda event: zoom_to_scale(event, 1000))

# to disconnect (and halt the behaviour)
#iface.mapCanvas().keyPressed.disconnect(con)

If you want the shortcut to be activated automatically when you open the project, you can make use of a macro.

Project > Properties > Macros > enable Python Macros checkbox

from qgis.utils import iface
from PyQt5.QtCore import Qt

def openProject():
    def zoom_to_scale(event, scale):
        if event.modifiers() & Qt.ControlModifier:
            if event.key() == Qt.Key_Y:
                iface.mapCanvas().zoomScale(scale)
                    
    con = iface.mapCanvas().keyPressed.connect(lambda event: zoom_to_scale(event, 1000))
1
  • Thank you Matt, your answer was spot on, a small tweak now sees activated three levels/buttons on the tablet, making my work easier.btw Matt, this is a variation on an answer you gave me 8 months ago.<br> You were most helpful then, as you are now.<br> Thank again, I'll really should try to find the time to learn QGIS customization properly. <br>Apologies to Babel, for fouling posting rules
    – glenndm
    Dec 18, 2023 at 14:40

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.