3

I have trouble assigning function to a hotkey in my plugin. I have a class that does things with a mouse click. I'd like to assign another function to a keyboard key or sequence. I've tried two different approaches:

  1. https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/snippets.html#how-to-call-a-method-by-a-key-shortcut This assigns given key sequence as a shortcut, but does nothing.

  2. def scale():
        iface.mapCanvas.zoomScale( 2500 )
    
    shortcut = QShortcut(QKeySequence(Qt.ControlModifier + Qt.Key_Q), iface.mainWindow())
    shortcut.setContext(Qt.ApplicationShortcut)
    shortcut.activated.connect(scale)
    

Both don't return any errors, but just doesn't work. I made sure that key sequences aren't in use. What am I missing?

1
  • It worked for me with a different shortcut sequence. Please, see my answer.
    – xunilk
    Commented Jan 15, 2019 at 16:16

1 Answer 1

3

Manually, I tried out your sequence placed at second code, Ctrl+Q, and it is assigned for quitting QGIS; as it can be observed at following image:

enter image description here

So, I modified slightly your code:

from PyQt4.QtCore import *
from PyQt4.QtGui import QShortcut, QKeySequence

def scale():
    iface.mapCanvas().zoomScale( 2500 )
    print "Hello"

shortcut = QShortcut(QKeySequence(Qt.ControlModifier + Qt.Key_F3), iface.mainWindow())
shortcut.setContext(Qt.ApplicationShortcut)
shortcut.activated.connect(scale)

for also printing "Hello" at Python Console and to assing Qt.Key_F3 to Qt.ControlModifier.

After running it at Python Console of QGIS, keyboard Ctrl + F3 sequence resulted as expected (following image). It was printed "Hello" at Python Console and scale was changed to 2500 (see red rectangles).

enter image description here

1
  • Thanks! Later I've noticed it too, but as it turned out, I needed a little bit more tinkering with where I want to put the key assignment part of code. InitGui() was the right place. Now it works like a charm.
    – Dreamscape
    Commented Jan 16, 2019 at 12: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.