4

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_()
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Vince W.
  • 3,561
  • 3
  • 31
  • 59

1 Answers1

3

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)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336