You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重写focusInEvent后QLineEdit闪烁光标消失,如何恢复?

解决PySide6中重写QLineEdit focusInEvent后光标消失的问题

问题根源

你的代码存在两个核心问题:

  1. 直接通过赋值lambda覆盖QLineEdit的focusInEvent方法,不符合Qt的事件重写规范,破坏了原有事件处理的继承链。
  2. 在自定义的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 06:12:04