Key Event Prevention

I have a simple application with one QPlainTextEdit, basically the same as the Qt example:

http://qt-project.org/doc/qt-5.1/qtwidgets/mainwindows-application.html

When I press Ctrl + Z, it causes the cancel. When I press Ctrl + A, it selects all the text. This is normal.

But when I press Ctrl + E or Ctrl + R, which are not defined in the menu, the characters "e" and "r" will appear in QSimpleTextEdit.

How to prevent this? How to "filter" keystrokes that were defined as menu shortcuts and keep them working, and "prevent" those keystrokes that are not defined as menu shortcuts that appear in the editor?

+6
source share
2 answers

There are 2 options:

1) Subclass and override keyPressEvent()

2) Create and use eventFilter installEventFilter() (see. Http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#installEventFilter )

+1
source

You can use the following code:

CSimpleEdit.h

 #include <QPlainTextEdit> class CSimpleEdit: public QPlainTextEdit { Q_OBJECT public: explicit CSimpleEdit(QWidget* parent = 0); ~ CSimpleEdit(); protected: bool eventFilter(QObject* obj, QEvent* event); }; 

CSimpleEdit.cpp

 CSimpleEdit::CSimpleEdit(QWidget* parent) : QPlainTextEdit(parent) { installEventFilter(this); } CSimpleEdit::~CSimpleEdit() { removeEventFilter(this); } bool CSimpleEdit::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->modifiers() != Qt::NoModifier && !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) { bool bMatch = false; for (int i = QKeySequence::HelpContents; i < QKeySequence::Deselect; i++) { bMatch = keyEvent->matches((QKeySequence::StandardKey) i); if (bMatch) break; } /*You can also set bMatch to true by checking you application *actions list -> QWidget::actions(). */ if (!bMatch) return true; } } else if (event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->modifiers() != Qt::NoModifier && !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) { bool bMatch = false; for (int i = QKeySequence::HelpContents; i < QKeySequence::Deselect; i++) { bMatch = keyEvent->matches((QKeySequence::StandardKey) i); if (bMatch) break; } if (!bMatch) return true; } } return QObject::eventFilter(obj, event); } 
+1
source

Source: https://habr.com/ru/post/955663/


All Articles