Tuom L.
Tuom L.

Reputation: 182

Preventing key events

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

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

When I press Ctrl+Z, it calls undo. When I press Ctrl+A, it selects all text. This is ok.

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

How do I prevent this? How to "filter" keypresses which have been defined as menu shortcuts and keep them working, and "prevent" those keypresses not defined as menu shortcuts from appearing in the edit?

Upvotes: 6

Views: 359

Answers (2)

delverdl
delverdl

Reputation: 83

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);
}

Upvotes: 1

Sebastian Lange
Sebastian Lange

Reputation: 4029

There are 2 options:

1) Create a subclass and reimplement keyPressEvent()

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

Upvotes: 1

Related Questions