python - 如何捕获Key_tab事件

标签 python pyqt4 keypress

我正在 try catch 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)

关于python - 如何捕获Key_tab事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802176/

相关文章:

python - 如何从用户中删除角色?

python - Scikit-learn - 无法在 Python 中使用 fetch_openml 加载 MNIST 原始数据集

ruby - 按 T​​AB 键,然后在带有 Ruby 的 Selenium WebDriver 中按 ENTER 键

c# - 在 WPF 应用程序中按下 Return 时如何模拟 Tab 键按下?

javascript - 如何在jquery中检测F5刷新按键事件?

python - Matplotlib:外部图例,分布在多个子图中

python - 如何使用 argparse 在单独的命名空间中使用子解析器参数?

ubuntu - 我应该怎么做才能让 PyQt4 工作?

python - Lambda 函数和变量作用域

python - 使用 QWorkspace 级联