自定义 QLineEdit 响应键盘事件
时间: 2024-02-15 20:10:29 浏览: 23
要让自定义的 QLineEdit 响应键盘事件,可以继承 QLineEdit 并重写其 keyPressEvent() 方法。
以下是一个简单的例子,当用户按下回车键时,会在控制台输出 QLineEdit 中的文本内容:
```python
from PyQt5.QtWidgets import QLineEdit, QApplication
from PyQt5.QtCore import Qt
import sys
class MyLineEdit(QLineEdit):
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
print(self.text())
super().keyPressEvent(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
line_edit = MyLineEdit()
line_edit.show()
sys.exit(app.exec_())
```
在这个例子中,我们继承了 QLineEdit 并重写了其 keyPressEvent() 方法。在该方法中,我们检查用户按下的键是否为回车键,如果是,则输出 QLineEdit 中的文本内容。
需要注意的是,在重写 keyPressEvent() 方法时,需要调用父类的 keyPressEvent() 方法,以保证 QLineEdit 的正常行为。