首页 > 解决方案 > 制表键是否未向 PyQt5 注册?

问题描述

使用下面的代码,除了 tab 键之外,每个键都会在终端中打印一些内容。tab 键仍然有效,我可以在行编辑之间切换。我只能捕捉事件。

# i'm using PyQt5==5.11.3 and 32 bit python 3.7.1

from PyQt5.QtWidgets import QLineEdit, QLabel, QWidget, QVBoxLayout, QApplication
import sys

class Main(QWidget):
    def __init__(self):
        super().__init__()
        label = QLabel('event')
        input1 = Input()
        input2 = Input()
        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(input1)
        layout.addWidget(input2)
        self.setLayout(layout)
        self.show()

class Input(QLineEdit):
    def __init__(self):
        super().__init__()

    def keyPressEvent(self, event):
        # why doesn't tab print anything
        print(event.key())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    wid = Main()
    sys.exit(app.exec_())

标签: pythonpython-3.xpyqt5

解决方案


event您可以使用QLineEdit中的方法拦截 tke Tab 按下事件。您处理您的事件,然后将其传递给 QLineEdit.event() 方法。

像这样的东西:

import sys

from PyQt5.QtCore import QEvent, Qt
from PyQt5.QtWidgets import QLineEdit, QLabel, QWidget, QVBoxLayout, QApplication

class Main(QWidget):
    def __init__(self):
        super().__init__()
        label = QLabel('event')
        input1 = Input()
        input2 = Input()
        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(input1)
        layout.addWidget(input2)
        self.setLayout(layout)
        self.show()

class Input(QLineEdit):
    def __init__(self):
        super().__init__()

    def keyPressEvent(self, event):
        print(event.key())

    def event(self,event):
        if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
            self.tabFollow()
        return QLineEdit.event(self,event)

    def tabFollow(self):
        print("tab-key pressed!")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    wid = Main()
    sys.exit(app.exec_())

推荐阅读