Trying to share a class (BodySuperClass), which can be either a QTextEdit or a QPlainTextEdit and contains Qt functions such as focusInEvent;
Also tried calling super().__init__() from the Body class, but that does not work;
What would be the best way to achive this?
#!/usr/bin/python3 from PyQt5 import QtWidgets class Text(QtWidgets.QWidget): def __init__(self): super().__init__() self.body = Body() self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.body) self.setLayout(self.layout) self.show() class BodySuperClass: def focusInEvent(self, event): print("Hello world") super().focusInEvent(event) class Body(QtWidgets.QPlainTextEdit, BodySuperClass): def __init__(self): super().__init__() app = QtWidgets.QApplication([]) widget = Text() app.exec()Which fails with;
Quote:Hello world
Traceback (most recent call last):
File "/tmp/pyScript.py", line 18, in focusInEvent
super().focusInEvent(event)
AttributeError: 'super' object has no attribute 'focusInEvent'
Also tried calling super().__init__() from the Body class, but that does not work;
#!/usr/bin/python3 from PyQt5 import QtWidgets class Text(QtWidgets.QWidget): def __init__(self): super().__init__() self.body = Body() self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.body) self.setLayout(self.layout) self.show() class BodySuperClass: def _monkeyInit(self, qTextClass): super(qTextClass, self).__init__() def focusInEvent(self, event): print("Hello world") super().focusInEvent(event) class Body(QtWidgets.QPlainTextEdit, BodySuperClass): def __init__(self): super().__init__() self._monkeyInit(QtWidgets.QPlainTextEdit) app = QtWidgets.QApplication([]) widget = Text() app.exec()Finally, what works is to hardcode inheritance of BodySuperClass to QPlainTextEdit, but I don't like that as when only a QTextEdit object is needed, Body inherits from both;
#!/usr/bin/python3 from PyQt5 import QtWidgets class Text(QtWidgets.QWidget): def __init__(self): super().__init__() self.body = Body() self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.body) self.setLayout(self.layout) self.show() class BodySuperClass(QtWidgets.QPlainTextEdit): def focusInEvent(self, event): print("Hello world") super().focusInEvent(event) class Body(QtWidgets.QTextEdit, BodySuperClass): def __init__(self): super().__init__() print("QTextEdit:", isinstance(self, QtWidgets.QTextEdit)) print("QPlainTextEdit:", isinstance(self, QtWidgets.QPlainTextEdit)) app = QtWidgets.QApplication([]) widget = Text() app.exec()
Quote:QTextEdit: True
QPlainTextEdit: True
Hello world
What would be the best way to achive this?