I'm trying to implement an event in PyQT5, but i get this error:
TypeError: installEventFilter(self, QObject): argument 1 has unexpected type 'MainWindow_EXEC'
This is my code
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()
The event that I'm trying to add is when I focus in a TextEdit it changes the value of a flag. If i change
self.ui.ledit_corteA.installEventFilter(self)
by
self.ui.ledit_corteA.installEventFilter(cortes2)
I works, but never changes the value of my flag.
Please help.
installEventFilter
expects a QObject
, and in your case MainWindow_EXEC
is not.
If you are using the Qt Designer design it is recommended to create a new class that inherits from the appropriate widget and use the class provided by Qt Designer to fill it as shown below:
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_())
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With