Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive Escape-Event in QLineEdit?

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!

like image 201
Elmi Avatar asked Jan 28 '15 10:01

Elmi


2 Answers

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 QLineEdits that need this behavior.

void MainWindow::setupLineEditKeyEventList()
{
    lineEditKeyEventSet.insert(ui->lineEdit_1);
    lineEditKeyEventSet.insert(ui->lineEdit_2);
    lineEditKeyEventSet.insert(ui->lineEdit_3);
}
like image 124
schmitt Avatar answered Nov 13 '22 00:11

schmitt


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);
like image 2
Nejat Avatar answered Nov 12 '22 23:11

Nejat