Reputation: 702
I have this code:
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (event->type() == QEvent::KeyPress)
{
if (keyEvent->key() == Qt::Key_Tab)
// do something
}
}
Now, I am typing in a QTextEdit. So say I hit the tab key. Then a tab will occur in the QTextEdit. But what if I want to prevent that from happening? For an analogy, if you are familiar with emacs: when in the right environment (say c++ mode), you can hit tab, and the line jumps to the right position (indenting). After hitting tab again, nothing happens. This is because the line of code is in the right position.
Anybody here knows how to do this? I guess I can let the tab event to be displayed in QTextEdit, and then delete previous char (or whatever it is defined as).
Upvotes: 3
Views: 2321
Reputation: 33627
You shouldn't need a global event filter to do special keyboard handling (unless for some reason, you can't edit the part where the widget is set to a QTextEdit). You can just derive a class from QTextEdit and override its virtual key methods:
http://doc.qt.io/qt-5/qwidget.html#keyPressEvent
To get the default behavior for a given keyEvent you would pass it through to QTextEdit::keyPressEvent()
, and to ignore it you would just return without calling that.
Upvotes: 2
Reputation: 17545
Using the return value of your event filter function will let you control which events your QTextEdit receives (if you really don't want to just subclass it):
if (keyEvent->key() == Qt::Key_Tab)
return true;
Returning true
indicates that the event should be filtered.
Upvotes: 3