python - 制表键是否未向 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_())
解决方案
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_())
推荐阅读
- laravel - Laravel 更新有很多关系
- javascript - 为什么我不能多次返回一个值——比如在 for 循环中?
- c# - 如何使用反射来获取与特定类型匹配的对象字段的值列表?
- c++ - 数组字符串空
- reactjs - 为什么我的应用程序在 React Dev 中有两个实例。工具?
- c# - 如何逐个元素浏览页面并确定我正在查看哪个元素?
- variables - 从 Ansible Facts 创建变量
- environment-variables - `gcloud functions deploy` 列出了所有环境变量——这可以避免吗?
- pyez - 在 EX4300 上使用 PyEZ
- r - 如何使用 lapply 根据条件使用多个功能