'How to write __init__ method inheriting two classes?
I have 3 class in my program. Base, Sub_1 and Sub2. Sub_1 inherits from Base and Sub_2 inherits from QThread and Base.
Base class has some pyQtSignal properties which I want other two classes to have. Now I have problem instantiating class Sub_2. When I run this code I get the following error:
QObject::connect: No such signal Sub_2::signal_1()
Traceback (most recent call last):
File "main.py", line 31, in <module>
win = MainWindow()
File "main.py", line 25, in __init__
self.worker.signal_1.connect(lambda: print('ok 1'))
TypeError: connect() failed between Base.signal_1[] and unislot()
main.py:
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QObject, pyqtSignal, QThread
class Base(QObject):
signal_1 = pyqtSignal()
signal_2 = pyqtSignal()
def __init__(self):
super(QObject, self).__init__()
class Sub_1(Base):
def __init__(self):
super().__init__()
class Sub_2(QThread, Base):
def __init__(self):
super().__init__()
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.worker = Sub_2()
self.worker.signal_1.connect(lambda: print('ok 1'))
self.worker.signal_2.connect(lambda: print('ok 2'))
import sys
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
Solution 1:[1]
There is no guarantee that QThread.__init__ properly supports multiple inheritance. The call to super().__init__() in Sub2 may therefore not initialize Base as you expect. You can fix this by changing your MRO.
To change the MRO:
class Sub_2(Base, QThread):
You might want to change Base to be more explicit in its support of multiple inheritance. Instead of super(QObject, self).__init__(), write
super().__init__()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
