
Originally Posted by
Cruz
The grabKeyboard() hack solves it all with one line and puts all keyboard handling in one place. It's easy to find, to understand, and to maintain.
I still think this is a hack. The sort of "offcial" way of providing your own event handling is to reimplement QCoreApplication::notify().
If grabKeyboard() works for you then that's fine. However if you are only after modifying some keys globally then using either of the two mentioned solutions (notify() or application event filter) is a more clean approach without getting you into a God Object design anti-pattern. Simply delegate the "custom" behaviours to a dedicated place and leave everything else to the default mechanism.
E.g.:
if(event->type() != Qt::KeyPressEvent) return false;
QKeyEvent *keyEvent
= static_cast<QKeyEvent
*>
(event
);
if(keyEvent->key() == Qt::Key_Left && object != myMainWindow) {
myMainWindow->keyPressEvent(keyEvent); // or do whatever else you'd like, e.g. event->ignore() letting it propagate until the main window
return true; // eat the left arrow key event
}
return false;
}
bool XXX::eventFilter(QObject *object, QEvent *event) {
if(event->type() != Qt::KeyPressEvent) return false;
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if(keyEvent->key() == Qt::Key_Left && object != myMainWindow) {
myMainWindow->keyPressEvent(keyEvent); // or do whatever else you'd like, e.g. event->ignore() letting it propagate until the main window
return true; // eat the left arrow key event
}
return false;
}
To copy to clipboard, switch view to plain text mode
Bookmarks