我正在尝试捕获key_tab事件,但是没有运气.我意识到只有在没有其他小部件的情况下它才起作用,因此光标没有去处,然后我才能使事件返回.这是一个简化的代码示例.
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_()
如果我注释掉以下两行
self.line = QLineEdit()
layout.addWidget(self.line)
那么就可以了,因为表单上只剩下一个小部件.
我要去哪里错了?
干杯,乔
解决方法:
显然,Key_Tab新闻事件从未传递给任何处理程序,而是传递给setFocus(),因此,为了拦截Key_Tab事件,我们需要自己实现event()方法.
所以这是新代码:
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)