Posted on

How to override QTextEdit shortcut key bindings

The only way to override the default shortcuts while the QTextEdit has focus is to intercept the QEvent::ShortcutOverride event. There are 2 ways to intercept this event: 1. write an event filter 2. subclass QTextEdit and then override the virtual event(QEvent* event) method. I prefer this 2nd method (pun intended) because anything that changes the functionality of a widget should probably be its own class.

Here is an example of how I block the QTextEdit from using all shortcuts that start with Ctrl being pressed:

bool CustomTextEdit::event(QEvent *event)
    if(event->type() == QEvent::ShortcutOverride)
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        if(keyEvent->modifiers().testFlag(Qt::ControlModifier) == true)
            // allow override of all Ctrl+ shortcuts
            return false;

    // normal procedure
    return this->QTextEdit::event(event);

Now that the QEvent::ShortcutOverride event has been used to cancel the shortcut, a QAction can be used to capture the shortcut calling setShortcut with the QKeySequence you wish to use. For example:


You can also setup the action directly in Qt Designer like this: