QShortcut on Key_Return prevents widget to properly handle the Enter key

Julien M Source

I would like a QAction to be fired when the Enter key is pressed, but I still want some QWidget to process the enter key when they need to, for instance in a QTextEdit or QLineEdit.
Ideally I would like to subclass QTextEdit and decide from here if I wand to process and "consume" the Enter event or if I want to let it propagate up to the QShortcut. However it doesn't seem to work like that

I have assigned this QShortcut to a given QAction

_mainWindow->actionStart->setShortcuts(QList<QKeySequence>() << Qt::Key_Return << Qt::Key_Enter);

Now when I press Enter while the focus is in a QWidget, the default behavior is not trigger. If I try to intercept a keyPressEvent, I don't catch anything. Is this the normal behavior?

My next attemps was to install an eventFilter on the MainWindow

    if( event->type() == QEvent::ShortcutOverride || event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease )
{
    QKeyEvent *ev = static_cast<QKeyEvent *>(event);
    if( ev->key()==Qt::Key_Return || ev->key()==Qt::Key_Enter )
    {
        QString receiver = obj->metaObject()->className();
        foreach(QString acc, _classEatEnter)
            if( receiver.contains(acc) )
            {
                 event->accept(); // Prevent event propagation to parents
                 return false;    // Allow obj to handle the "Enter" event
            }
    }

Now I can filter the sender class and let some of them process the Enter event.

But what I would like to do is to let my subclass decide if it has anything to do with the keyPress event and if not, let the QShortcut process it.

c++qtshortcut

Answers

comments powered by Disqus