This is a bit of a beginners question but I don't find the solution.
I'm using an own object that inherits from QLineEdit
and reiceves numbers as input (which works smoothly now).
Now I want to receive an event, when the user presses the Escape-button. This does not happen with the textChanged()
-event. According to the documentation there is no special escape-event. So how else can this be done?
Thanks!
I had this same problem. I am solving it by implementing keyPressEvent
in my QMainWindow
.
void MainWindow::keyPressEvent(QKeyEvent *e)
{
if (e->key() == Qt::Key_Escape) {
QLineEdit *focus = qobject_cast<QLineEdit *>(focusWidget());
if (lineEditKeyEventSet.contains(focus)) {
focus->clear();
}
}
}
And setting up QSet<QLineEdit *> lineEditKeyEventSet
to contain the QLineEdit
s that need this behavior.
void MainWindow::setupLineEditKeyEventList()
{
lineEditKeyEventSet.insert(ui->lineEdit_1);
lineEditKeyEventSet.insert(ui->lineEdit_2);
lineEditKeyEventSet.insert(ui->lineEdit_3);
}
You can either implement keyPressEvent
:
void LineEdit::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape)
{
...
}
QLineEdit::keyPressEvent(event);
}
Or implement eventFilter
:
bool LineEdit::eventFilter(QObject *obj, QEvent * event)
{
if((LineEdit *)obj == this && event->type()==QEvent::KeyPress && ((QKeyEvent*)event)->key() == Qt::Key_Escape )
{
...
}
return false;
}
When using the eventFilter
approach, install the event filter in the constructor :
this->installEventFilter(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With