PyQt5 在 pyuic 生成的代码之外添加 eventFilter

PyQt5 add eventFilter outside of pyuic generated code

我是这里的 Qt 新用户。 我有一个项目,我要在其中使用 pyuic 生成的 .py 文件,但我无权访问它。

我还应该在某些对象上安装事件过滤器。是否可以在 object.installEventFilter() 外部 生成的 .py 文件中使用?

main_window.py

class Ui_MainWindow(QtWidgets.QMainWindow):
self.titleLabel = QtWidgets.QLabel(MainWindow)

Frontend.py

from PyQt5 import QtCore, QtGui, QtWidgets
from main_window import Ui_MainWindow

class Session (object):

    def __init__(self):
        self.mainUI = None

    def eventFilter(self, source, event):
        eventReturn = False
        if(event.type() == QtCore.QEvent.MouseButtonDblClick and
           source is self.lblTitle):
            eventReturn = self._labelTitle(source, event)

        return eventReturn

    def _labelTitle(self, widget, event):
        retVal = True
        print("works, Title")

def GUIcontroller():
    import sys

    app = QtWidgets.QApplication(sys.argv)

    thisSession = Session()

    MainWindow = QtWidgets.QMainWindow()
    thisSession.mainUI = Ui_MainWindow()
    thisSession.mainUI.setupUi(MainWindow)
    thisSession.mainUI.titleLabel.installEventFilter(???)

    MainWindow.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    GUIcontroller()

事件过滤器仅在 QObjects 中有效,而在您的代码中使用的对象将不起作用,考虑到上述情况,一个可能的解决方案是:

from PyQt5 import QtCore, QtGui, QtWidgets

from main_window import Ui_MainWindow


class Session(QtCore.QObject):
    def __init__(self, ui):
        super().__init__(ui)
        self._ui = ui
        self.ui.installEventFilter(self)

    @property
    def ui(self):
        return self._ui

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseButtonDblClick and source is self.ui:
            print("double clicked")
        return super().eventFilter(source, event)


def GUIcontroller():
    import sys

    app = QtWidgets.QApplication(sys.argv)

    MainWindow = QtWidgets.QMainWindow()

    mainUI = Ui_MainWindow()
    mainUI.setupUi(MainWindow)

    thisSession = Session(mainUI.titleLabel)

    MainWindow.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    GUIcontroller()