我正在尝试在PyQT5中实现一个事件,但是我收到了这个错误:
TypeError: installEventFilter(self, QObject): argument 1 has unexpected type 'MainWindow_EXEC'
这是我的代码
import sys
from time import sleep
from PyQt5 import QtCore, QtWidgets
from view_cortes2 import Ui_cortes2enter
class MainWindow_EXEC():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
cortes2 = QtWidgets.QMainWindow()
self.ui = Ui_cortes2()
self.ui.setupUi(cortes2)
self.flag = 0
self.ui.ledit_corteA.installEventFilter(self)
self.ui.ledit_corteB.installEventFilter(self)
self.ui.buttonGroup.buttonClicked.connect(self.handleButtons)
cortes2.show()
sys.exit(app.exec_())
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.FocusIn and source is self.ui.ledit_corteA):
print("A")
self.flag = 0
if (event.type() == QtCore.QEvent.FocusIn and source is self.ui.ledit_corteA):
print("B")
self.flag = 1
return super(cortes2, self).eventFilter(source, event)
if __name__ == "__main__":
MainWindow_EXEC()
我想要添加的事件是当我专注于TextEdit时,它会更改标志的值。如果我改变
self.ui.ledit_corteA.installEventFilter(self)
通过
self.ui.ledit_corteA.installEventFilter(cortes2)
我工作,但从不改变我的旗帜的价值。
请帮忙。
答案 0 :(得分:3)
installEventFilter
需要QObject
,而您的MainWindow_EXEC
则不是。
如果您使用的是Qt Designer设计,建议您创建一个继承自相应小部件的新类,并使用Qt Designer提供的类来填充它,如下所示:
import sys
from PyQt5 import QtCore, QtWidgets
from view_cortes2 import Ui_cortes2
class MainWindow(QtWidgets.QMainWindow, Ui_cortes2):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.flag = 0
self.ledit_corteA.installEventFilter(self)
self.ledit_corteB.installEventFilter(self)
#self.buttonGroup.buttonClicked.connect(self.handleButtons)
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.FocusIn and source is self.ledit_corteA:
print("A")
self.flag = 0
if event.type() == QtCore.QEvent.FocusIn and source is self.ledit_corteB:
print("B")
self.flag = 1
return super(MainWindow, self).eventFilter(source, event)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
参考文献: