Respond to application-wide "hotkey" in Qt
I haven't tried, but here is what I would do :
Create a QShortcut and make sure its context (with setContext()
) is Qt::ApplicationShortcut
.
shortcut = new QShortcut(QKeySequence(Qt::Key_F12), parent);
shortcut->setContext(Qt::ApplicationShortcut);
Then you just need to connect a slot to the QShortcut::activated() signal.
Setting the shortcut context to Qt::ApplicationShortcut
has a serious flaw. It will not work in modal dialogs. So if you want a trully real pan-application-wide shortcut, then you need to override application's notify()
method. The alternative is to install event filter for the application object but that I suspect would be slower and requires slightly more code. With notify()
it is very simple:
class MyApplication : public QApplication
{
// TODO: constructor etc.
protected:
bool MyApplication::notify(QObject *receiver, QEvent *event) override
{
if (event->type() == QEvent::KeyPress)
{
auto keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_F12 && keyEvent->modifiers() == Qt::NoModifiers)
{
// TODO: do what you need to do
return true;
}
}
return QApplication::notify(receiver, event);
}
}
If you have a "central widget" which all of the other widgets are children of, then you can simply set that as the widget argument for QShortcut.
(Python, qt5)
self.centralwidget = QtWidgets.QWidget(MainWindow)
QtWidgets.QShortcut(QtGui.QKeySequence("F12"), self.centralwidget, self.goFullScreen)
I added this as an answer because the shortcut context flag: Qt.ApplicationShortcut
did not work for me.