我是这里的 Qt 新用户。
我有一个项目,我要使用 pyuic 生成的 .py
文件,但我无权访问它。
我还应该在某些对象上安装事件过滤器。是否可以在生成的 .py
文件之外使用 object.installEventFilter()
?
main_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/