2

我正在尝试捕获 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)

然后它工作正常,因为表单上只剩下一个小部件。

我哪里错了?

干杯,乔

4

1 回答 1

1

显然 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)
于 2013-04-18T04:31:34.833 回答