pythonpyqtpyqt5eventfilter

PyQt5 add eventFilter outside of pyuic generated code


I'm a new Qt user here. I've got a project where I'm to use a pyuic generated .py file but I don't have access to it.

I'm also supposed to be installing event filters on some of the objects. Is it possible to use object.installEventFilter() outside the generated .py file?

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()

Solution

  • The event filters only work in the QObjects, and in your code you use object that will not work, considering the above a possible solution is:

    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()