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

标签 python pyqt pyqt5 eventfilter

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

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

ma​​in_window.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()

最佳答案

事件过滤器仅在 QObject 中工作,并且在您的代码中您使用的对象将不起作用,考虑到上述可能的解决方案是:

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

关于python - PyQt5 在 pyuic 生成的代码之外添加 eventFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59517416/

相关文章:

python - 使用 Python PIL 和 Windows API : how to deal with rounded corners? 的事件窗口屏幕截图

javascript - 带有 PYQT QWebView 的谷歌地图 API

python - Pandas 数据框到列表字典

2 个列表的 Python 组合(1 个重复,1 个不重复)

python - QWidget 无法捕获 ESCAPE、BACKSPACE 或 C-x 按键事件

python - 多重继承元类冲突

python - 你如何从 sip.voidptr (QImage.constBits()) 到 ctypes void 或 char 指针?

python - 我创建了一个带有复选框的组合框,但是当选中复选框时我无法捕获该事件

python - gui 在处理过程中没有响应?

python - Caffe 中的预测 - 异常 : Input blob arguments do not match net inputs