How to make QPushButton not to be triggered by Enter keyboard key

此生再无相见时 提交于 2020-06-27 03:49:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!