我构建了一个(单例)服务类,其中包括“ something_changed”信号。该服务包含在基本父类中,并在其中连接到插槽。从该父类中,派生了两个子类Child1和Child2,它们都在main方法中初始化。
当我发送信号时,似乎仅执行了最后一个连接的子级的插槽(似乎与文档和其他来源,例如here相比)只有一个连接是可能的。
为演示我的问题,我简化了类:
Service.py
from PyQt5.QtCore import QObject, pyqtSignal
class Service(QObject):
__instance = None
something_changed = pyqtSignal()
def __new__(cls) -> "Service":
if cls.__instance is None:
print("Creating new service instance")
cls.__instance = QObject.__new__(cls)
else:
print("Returning existing service instance")
return cls.__instance
def do_something(self):
print("Do something")
self.something_changed.emit()
Classes.py
from PyQt5.QtCore import QObject
from Service import Service
class Parent(QObject):
def __init__(self):
super().__init__()
self._service = Service()
self._service.something_changed.connect(self._something_changed)
print("Init Parent: " + self.__class__.__name__)
def _something_changed(self):
print("Parent - _something_changed: " + self.__class__.__name__)
class Child1(Parent):
def __init__(self):
super().__init__()
print("Init Child1: " + self.__class__.__name__)
def _something_changed(self):
print("Child1 - _something_changed: " + self.__class__.__name__)
class Child2(Parent):
def __init__(self):
super().__init__()
print("Init Child2: " + self.__class__.__name__)
def _something_changed(self):
print("Child2 - _something_changed: " + self.__class__.__name__)
main.py
from Classes import Child1, Child2
from Service import Service
if __name__ == "__main__":
service = Service()
child1 = Child1()
child2 = Child2()
service.do_something()
以及结果输出:
Creating new service instance
Returning existing service instance
Init Parent: Child1
Init Child1: Child1
Returning existing service instance
Init Parent: Child2
Init Child2: Child2
Do something
Child2 - _something_changed: Child2
我期望并且也试图实现的目标是在信号发出时从两个孩子运行“ _something_changed”功能。
其他节点:
当我评论child2 = Child2()
初始化时,将调用child1的“ _something_changed”功能,因此必须建立连接。
谢谢