PDA

View Full Version : Handling keypress event in textedit



Niamita
14th December 2011, 10:27
HI all

I want to handle key event when i type anything in textedit.
I am doing it likethis


bool HomeWindow::eventFilter(QObject *object, QEvent *event) {

if (object == condition_text_edit && event->type() == QEvent::KeyPress)
{ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key())
{
qDebug("Enter Key Pressed...");
qDebug()<<keyEvent->key();
textedit.setText(keyEvent.text());
return true;
}
}

It is handling keys one by one but i want to handle event when i typed in textedit so that i can prevent some keys from typing in textedit.

Please suggest me how should i handle key event.

Thanks

stampede
14th December 2011, 11:07
It needs few corrections:

bool HomeWindow::eventFilter(QObject *object, QEvent *event) {
if (object == condition_text_edit && event->type() == QEvent::KeyPress)
{ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
// key() returns the code of the key that was pressed, so you need to compare it with the keys you want to filter out, for example 'A' character
// see the QKeyEvent::key docs for complete list of key codes
if (keyEvent->key() == Qt::Key_A)
{
qDebug("Enter Key Pressed...");
qDebug()<<keyEvent->key();
// now it will be impossible to type the 'A' char into text edit
return true;
}
}
return QWidget::eventFilter(object,event); // you need to call base class implementation to save "normal" behavior
}