Elmi
Elmi

Reputation: 6213

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!

Upvotes: 6

Views: 2790

Answers (3)

Jim
Jim

Reputation: 648

You can define a QAction with Esc keyboard shortcut.

For instance I do that to auto-close a popup edit in a more complex widget:

auto edit = new QLineEdit(this);
// ...
auto action = new QAction(edit);
action->setShortcut(Qt::Key_Escape);
edit->addAction(action);
connect (action, &QAction::triggered, [edit](){
  edit->hide();
});

(hiding make the QLineEdit lose focus, so editingFinished() signal will fires)

Upvotes: 0

schmitt
schmitt

Reputation: 347

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);
}

Upvotes: 3

Nejat
Nejat

Reputation: 32695

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);

Upvotes: 3

Related Questions