重写focusInEvent后QLineEdit闪烁光标消失,如何恢复?
解决PySide6中重写QLineEdit focusInEvent后光标消失的问题
问题根源
你的代码存在两个核心问题:
- 直接通过赋值
lambda覆盖QLineEdit的focusInEvent方法,不符合Qt的事件重写规范,破坏了原有事件处理的继承链。 - 在自定义的
on_focus_in_event中调用self.edt.setFocus(),会触发无限循环的焦点事件,且完全跳过了QLineEdit内置的焦点处理逻辑(包括光标显示)。
正确解决方案
通过子类化QLineEdit来重写focusInEvent,并在自定义逻辑后调用父类的事件方法,确保原有功能正常执行:
from PySide6.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton class CustomLineEdit(QLineEdit): def focusInEvent(self, event): # 执行你的自定义逻辑 print("Doing something") # 调用父类的focusInEvent,让QLineEdit处理光标显示等原生逻辑 super().focusInEvent(event) class MyWindow(QMainWindow): def __init__(self): super().__init__() # 使用自定义的LineEdit子类 self.edt = CustomLineEdit(self) self.edt.move(10, 10) self.btn = QPushButton("OK", self) self.btn.move(10, 50) if __name__ == '__main__': app = QApplication() window = MyWindow() window.show() app.exec()
方案说明
- 子类化是Qt重写事件的标准方式,能保证事件处理流程的正确性。
super().focusInEvent(event)会触发QLineEdit原本的焦点处理逻辑,包括显示闪烁光标、处理焦点状态等。- 移除了多余的
setFocus()调用,避免无限循环和焦点状态混乱。
内容的提问来源于stack exchange,提问作者jalexm123
相关产品推荐
相关产品推荐

