Get Escape-Event in QLineEdit?

This is a little newbie, but I did not find a solution.

I use a native object that inherits from QLineEditand 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 textChanged()-event. According to the documentation there is no special escape event. So how can this be done?

Thank!

+4
source share
2 answers

I had the same problem. I solve this by implementing keyPressEventin mine 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 customization QSet<QLineEdit *> lineEditKeyEventSetto contain QLineEditwho need it.

void MainWindow::setupLineEditKeyEventList()
{
    lineEditKeyEventSet.insert(ui->lineEdit_1);
    lineEditKeyEventSet.insert(ui->lineEdit_2);
    lineEditKeyEventSet.insert(ui->lineEdit_3);
}
+2

keyPressEvent:

void LineEdit::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape)
    {
        ...
    }

    QLineEdit::keyPressEvent(event);
}

eventFilter:

bool LineEdit::eventFilter(QObject  *obj, QEvent * event)
{

    if((LineEdit *)obj == this && event->type()==QEvent::KeyPress && ((QKeyEvent*)event)->key() == Qt::Key_Escape )
    {
        ...
    }

    return false;
}

eventFilter :

this->installEventFilter(this);
+1

All Articles