如何在不子类化的情况下为 QTextEdit 小部件定义 mousePressEvent 函数?

How to define a mousePressEvent function for a QTextEdit widget without subclassing it?

class widget(QWidget):
    ...
        self.edit=QTextEdit()

    def mousePressEvent(self, event):
        if event.button()==Qt.LeftButton:
            print('test')
        self.edit.mousePressEvent(event)

我已经试过了,但是没有用。它适用于父小部件。无论如何我可以在不子类化 QTextEdit 的情况下做到这一点?

在这种情况下,除了从 QAbstractScrollArea 继承的 类 之外,您还必须使用 eventFilter 作为 QTextEdit 您必须使用 viewport()

from PyQt5 import QtCore, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.edit = QtWidgets.QTextEdit()
        btn = QtWidgets.QPushButton()
        le = QtWidgets.QLineEdit()

        lay = QtWidgets.QVBoxLayout(self)
        for w in (self.edit, btn, le):
            lay.addWidget(w)

        self.edit.viewport().installEventFilter(self)

    def eventFilter(self, obj, event):
        if obj is self.edit.viewport() and event.type() == QtCore.QEvent.MouseButtonPress:
            if event.button() == QtCore.Qt.LeftButton:
                print('test')
        return super(Widget, self).eventFilter(obj, event)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())