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

如何在PyQt6的QPlainTextEdit中捕获鼠标左键点击事件?

解决PyQt6中QPlainTextEdit鼠标左键点击事件捕获失败的问题

问题原因

QPlainTextEdit的鼠标左键事件会被其内部的viewport(负责渲染文本的核心区域)处理,而非QPlainTextEdit本身。之前的两种方法要么监听了主窗口的事件(主窗口无法获取被子组件拦截的左键事件),要么给QPlainTextEdit本身安装了事件过滤器(但事件已被viewport接收并消费),因此无法捕获左键点击。

解决方法

方法一:给viewport安装事件过滤器

直接对QPlainTextEdit的viewport组件安装事件过滤器,即可捕获所有鼠标事件:

#!/usr/bin/env python3
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
from PyQt6.QtCore import QEvent

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.qpte = QPlainTextEdit("Click in this window")
        # 给viewport而非QPlainTextEdit本身安装事件过滤器
        self.qpte.viewport().installEventFilter(self)
        self.setCentralWidget(self.qpte)

    def eventFilter(self, obj, event):
        if obj is self.qpte.viewport():
            if event.type() == QEvent.Type.MouseButtonPress:
                if event.button() == event.button().LeftButton:
                    print("左键点击触发")
                else:
                    print(f"其他按键点击: {event.button()}")
            elif event.type() == QEvent.Type.MouseMove:
                print("鼠标移动触发")
            elif event.type() == QEvent.Type.MouseButtonRelease:
                print("按键释放触发")
        # 返回False,让事件继续传递,保留QPlainTextEdit原有功能
        return super().eventFilter(obj, event)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

方法二:子类化QPlainTextEdit并重写鼠标事件

通过子类化QPlainTextEdit,重写其mousePressEvent方法,直接捕获左键事件:

#!/usr/bin/env python3
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
from PyQt6.QtGui import QMouseEvent

class CustomPlainTextEdit(QPlainTextEdit):
    def __init__(self, text='', parent=None):
        super().__init__(text, parent)

    def mousePressEvent(self, e: QMouseEvent) -> None:
        if e.button() == e.button().LeftButton:
            print("左键点击触发")
        # 调用父类方法,确保文本编辑的原有功能正常
        super().mousePressEvent(e)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.qpte = CustomPlainTextEdit("Click in this window")
        self.setCentralWidget(self.qpte)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

注意事项

  • 无论使用哪种方法,都必须确保事件能继续传递(方法一返回False,方法二调用父类的mousePressEvent),否则QPlainTextEdit的核心功能(如光标定位、文本选择)会失效。

内容的提问来源于stack exchange,提问作者jthornton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:07:02