Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_()
like image 543
Vince W. Avatar asked Oct 26 '25 15:10

Vince W.


1 Answers

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)
like image 105
ekhumoro Avatar answered Oct 29 '25 05:10

ekhumoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!