gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:14 25 4
gpt4 key购买 nike

我是这里的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com