如何捕获Key_tab事件 [英] How to capture the Key_tab event
问题描述
我正在尝试捕获key_tab事件,但是没有运气.我意识到只有在没有其他小部件的情况下它才起作用,因此光标没有地方可以去,只有这样我才能使事件返回.这是一个简化的代码示例.
i am trying to capture the key_tab event, but no luck. i realized that it only works if there are no other widgets so the cursor has no where to go only then can i get the event to return. here is a simplified code sample.
class MyCombo(QComboBox):
def __init__(self, parent=None):
super(MyCombo, self).__init__(parent)
self.setEditable(True)
def keyPressEvent(self, event):
if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Tab):
print "tab pressed"
elif event.key() == Qt.Key_Return:
print "return pressed"
else:
QComboBox.keyPressEvent(self, event)
class Form_1(QDialog):
def __init__(self, parent=None):
super(Form_1, self).__init__(parent)
self.combo = MyCombo()
self.line = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(self.combo)
layout.addWidget(self.line)
self.setLayout(layout)
app = QApplication(sys.argv)
form = Form_1()
form.show()
app.exec_()
如果我将以下两行注释掉
if i comment out the following two lines
self.line = QLineEdit()
layout.addWidget(self.line)
然后它可以正常工作,因为表单上只剩下一个小部件.
then it works fine, because there is only one widget left on the form.
我要去哪里错了?
干杯,乔
推荐答案
很显然,Key_Tab按下事件从未传递给任何处理程序,而是传递给setFocus(),因此,为了拦截Key_Tab事件,我们需要实现事件( )方法本身. 所以这是新代码:
Apparently the Key_Tab press event is never passed to any handler but to the setFocus() so in order to intercept the Key_Tab event, we need to implement the event() method itself. so here is the new code:
class MyCombo(QComboBox):
def __init__(self, parent=None):
super(MyCombo, self).__init__(parent)
self.setEditable(True)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
print "return pressed"
else:
QComboBox.keyPressEvent(self, event)
def event(self, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
print "tab pressed"
return False
return QWidget.event(self, event)
class Form_1(QDialog):
def __init__(self, parent=None):
super(Form_1, self).__init__(parent)
self.combo = MyCombo()
self.line = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(self.combo)
layout.addWidget(self.line)
self.setLayout(layout)
这篇关于如何捕获Key_tab事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!