PyQt5在pyuic生成的cod之外添加eventFilter

2024-10-02 00:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

主窗口.py

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

前端.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()

Tags: 文件pyimportselfeventuisourceobject
1条回答
网友
1楼 · 发布于 2024-10-02 00:25:19

事件筛选器仅在QoObject中起作用,在代码中使用的对象不起作用,考虑到上述情况,可能的解决方案是:

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

相关问题 更多 >

    热门问题