How to set up shortcuts from module on startup?

Hi, to register keyboard shortcuts from a scripted module i have been putting the code in the setup method of my widget class, however there is a need to run each module to register its shortcuts, where should shortcut registration be placed in a module so it can run as soon as slicer starts?
I tried setting it as a separate method in widget class then call it but then i get "Failed to obtain reference to ‘qSlicerMainWindow’ " error

def Register_Shortcuts():
    def funct():
    shortcuts = [
        ('x', funct),
        ('b', funct)]
    for (shortcutKey, callback) in shortcuts:
        shortcut = qt.QShortcut(slicer.util.mainWindow())
        shortcut.connect('activated()', callback)

Hi -

A couple options - if it’s just for the user you can put the code in ~/ Or if you want this to be part of the module you can use the startupComplete() signal from the application to trigger the code.

1 Like

Thanks a lot.
Indeed slicerrc needs to be edited which is not ideal for module sharing.
startupComplete() signal is exactly what i was looking for. Thanks a lot for your help.

Note to interested people: i had to put in the init method of the main module class to be run at slicer’s startup

If there is a risk of shortcuts conflicting between modules, and you only want to use specific shortcuts in your module, you could have a look at this example (search for “shortcut” in the code). It installs shortcuts when you enter the module, but uninstalls them when you switch to a different module.


Thanks for the precision, that will definitely come in handy,
i don’t see how enter and exit methods (lines 317 and 375) get called? do slicer recognize their names and runs them automatically like the setup method?

yes, it does automatically call them

1 Like

Quite useful, Thanks for your help!

Dear Tamas,
Could you please reload the link?

It’s better to take examples from the official script repository: Script repository — 3D Slicer documentation

But here it is:

1 Like