Important: Please read the Qt Code of Conduct -

QLineEdit::returnPressed closes dialog

  • Hi, I have a dialog with a line edit controls.
    By default the dialog ok button has the focus which is fine.
    My problem is, that if the return key is pressed while editing the line edit the dialog closes.
    What is the correct way to fix that?

  • Lifetime Qt Champion

    Did you use your own QPushButton for Ok/Cancel or did you use the QDialogButtonBox ?

  • I am using QDialogButtonBox

  • I tried listening to editingFinished and set the focus to the line edit, but it didn't help

  • Turn off the OK button as the default button.
    From the doc:

    If you want a specific button to be default you need to call
     QPushButton::setDefault() on it yourself. However, if there is no
     default button set and to preserve which button is the default button 
    across platforms when using the QPushButton::autoDefault property, 
    the first push button with the accept role is made the default button 
    when the QDialogButtonBox is shown,

  • Lifetime Qt Champion

    As @mpergand says, QDialogButtonBox will help you and find a new default button even if you
    say there is no default. Also if you set Cancel as default, it will still close the dialog.
    I cant promise its the best way to solve it but overriding keyPressEvent worked fine
    for me and also gave me the option to make enter/return into tab so pressing return would move
    to next lineEdit. (not shown)

    class Dialog : public QDialog
        virtual void keyPressEvent(QKeyEvent *event) override
            int key = event->key();
            if (key == Qt::Key_Return || key == Qt::Key_Enter)

Log in to reply