Vince W.
Vince W.

Reputation: 3785

Prevent okay QPushButton from accepting dialog on press enter

In the following code, the Ok button of the dialog always seems to come into focus, thus when enter is pressed, the dialog is accepted and closes. What I am aiming for is that to have the user edit text in the line edit, and then be allowed to press enter when done to process the text (editingFinished signal). However, this triggers the Ok button accepting the dialog. Is there a way to disable this without subclassing the dialog?

from PyQt5 import QtWidgets
import sys

app = QtWidgets.QApplication(sys.argv)

widget = QtWidgets.QWidget()
dbutton = QtWidgets.QPushButton("Show Dialog", widget)

dialog = QtWidgets.QDialog(None)
vlay = QtWidgets.QVBoxLayout(dialog)
form = QtWidgets.QFormLayout(None)
vlay.addLayout(form)

form.addRow("Text Input", QtWidgets.QLineEdit())
form.addRow("Float Input", QtWidgets.QSpinBox())

ok = QtWidgets.QPushButton("Ok")
cancel = QtWidgets.QPushButton("Cancel")
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(ok)
hlay.addWidget(cancel)
vlay.addLayout(hlay)
ok.clicked.connect(dialog.accept)
cancel.clicked.connect(dialog.reject)

dbutton.clicked.connect(dialog.exec_)
widget.show()

app.exec_()

Upvotes: 4

Views: 2888

Answers (1)

ekhumoro
ekhumoro

Reputation: 120608

You must change the auto default settings on the two buttons:

ok = QtWidgets.QPushButton("Ok")
ok.setAutoDefault(False)
cancel = QtWidgets.QPushButton("Cancel")
cancel.setAutoDefault(False)

Upvotes: 3

Related Questions