问题
The code below creates a single dialog window with 5 buttons. Each button is connected to onClick
function. If I hit 'Enter' keyboard key one of the buttons is triggered and it onClick
function is executed.
How to change the buttons properties so the buttons call for onClick
function only when they are clicked and do not respond to Enter
keyboard key?
from PyQt4 import QtGui
def onClick():
print 'button clicked'
dialog = QtGui.QDialog()
dialog.setLayout(QtGui.QVBoxLayout())
for i in range(5):
btn = QtGui.QPushButton('Button %03d'%i)
btn.clicked.connect(onClick)
dialog.layout().addWidget(btn)
dialog.show()
回答1:
Set the default
and autoDefault
property of the QPushButtons
to False. E.g.
btn = QtGui.QPushButton('Button %03d'%i, default=False, autoDefault=False)
What you are observing is the the QDialog's special handling of the enter key to trigger the default 'dialog action' (it is a common gotcha when using QDialog).
来源:https://stackoverflow.com/questions/44005056/how-to-make-qpushbutton-not-to-be-triggered-by-enter-keyboard-key