如何使 QPushButton 不被 Enter 键盘键触发 [英] How to make QPushButton not to be triggered by Enter keyboard key
问题描述
下面的代码创建了一个带有 5 个按钮的对话窗口.每个按钮都连接到 onClick
函数.如果我按下Enter"键盘键,则会触发其中一个按钮并执行 onClick
函数.
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.
如何更改按钮属性,使按钮仅在单击时调用onClick
函数,而不响应Enter
键盘键?
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()
推荐答案
将 QPushButtons
的 default
和 autoDefault
属性设置为 False.例如
Set the default
and autoDefault
property of the QPushButtons
to False. E.g.
btn = QtGui.QPushButton('Button %03d'%i, default=False, autoDefault=False)
您观察到的是 QDialog 对 Enter 键的特殊处理以触发默认 'dialog action'(这是使用 QDialog 时的常见问题).
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).
这篇关于如何使 QPushButton 不被 Enter 键盘键触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!