rwx
rwx

Reputation: 595

QTextEdit - How to "cancel" entered key codes in onKeyPress()

I am trying to "cancel" key codes in QTextEdit or QPlainTextEdit. When I say cancel, what I mean is, I want to turn the "entered" character into "nothing" depending on the key entered. Example: if the user hits "a" or "b" on the keyboard, I would not want to have "a" or "b" displayed / entered into the text, instead, the input would be ignored and turned into nothing / won't be processed.

With C++ Builder, you have a KeyDown_Event and a "Key" parameter. Once you detect the entered key code, if you don't like it, you can set the "Key" parameter to 0, so you set "Key = 0" and the key stroke would not be displayed. How do I achieve the same thing in Qt?

Let me explain with code:

if (e->key() == 67)
    // do not send "c" to the QTextEdit (In C++ Bullder, you would do Key = 0)

if (e->key() == 65)
    // do not send "a" to the QTextEdit (In C++ Bullder, you would do Key = 0)

How do I do this in Qt?

I tired doing e->setAccepted(false) and e->Ignore() but it made no difference. I think by the time e->ignore() is executed, the "char" is already inserted into the text box. With C++ Builder, you can intercept this with the KeyDown event and cancel it. I can't seem to find a way with Qt.

Thx

Upvotes: 0

Views: 1221

Answers (1)

Amartel
Amartel

Reputation: 4286

Similar to void QObject::installEventFilter ( QObject * filterObj ) example:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setupUi(this);

    textEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == textEdit && event->type() == QEvent::KeyPress) {
        QKeyEvent *e = static_cast < QKeyEvent * >(event);
        if (e->key() == Qt::Key_A) {
            return true;
        }
    }
    return QMainWindow::eventFilter(watched, event);
}

UPDATE

As IInspectable noticed, this won't help you with filtering Ctrl+C/Ctrl+V method. If you need these either, you'll need to connect to QTextEdit::textChanged signal and updated the text manually. Something like this:

static QString oldString;
QString s = textEdit->toPlainText();
if (s == oldString)
   return;
int pos = textEdit->textCursor().position();
s.remove('a', Qt::CaseInsensitive);
oldString = s;
textEdit.setPlainText(s);
QTextCursor cursor = textEdit->textCursor();
cursor.setPosition(pos);
textEdit->setTextCursor(cursor);

Upvotes: 2

Related Questions