我在一个Python应用程序中工作,使用Raspberry Pi上的PySide和Raspbian Jessie OS。
我是Python的新手,我根本不是专家。所以这可能是一个乞丐的问题。
在我的申请中,我有:
在一些subyacent线程代码的地方,我需要发出一个必须由主线程捕获的信号。在之前的版本中,我这样做了:
#Slot for clicked button
def Slot_Start_Calculation (self):
self.MyLongThread = QThread()
MyLongWorker = MyWorker(self, Qty)
MyLongWorker.moveToThread(self.MyLongThread)
self.MyLongThread.started.connect(MyLongWorker.Run_LongWorker)
MyLongWorker.WorkerFinished.connect(self.MyLongThread.quit)
MyLongWorker.WorkerFinished.connect(self.MyLongWorker.deleteLater)
MyLongThread.finished.connect(self.MyLongThread.deleteLater)
MyLongThread.start()
def Slot_Worker_Sent_A_Signal (self, Result):
print ("Worker sent this result: " + str(Result))
.
.
.
class MyWorker(QObject):
WorkerFinished = Signal()
CustomSignal = Signal(int)
def __init__(self, parent, Quantity)
super().__init__(parent)
self_parent = parent
self.Quantity = Quantity
print("Myworker's constructor")
def __del__(self):
print("Myworker's destructor")
def Run_LongWorker (self):
self.CustomSignal.connect(self.parent.Slot_Worker_Sent_A_Signal)
.
.
.
self.CustomSignal.emit(MyPartialResult)
.
.
.
self.WorkerFinished.emit()
此代码在几周前的测试环境中运行,同时我完成了GUI的一些细节,我没有看到任何错误。 昨天在网上搜索我随便注意到QObject :: moveToThread无法移动父对象
的https:// forum.qt.io/topic/40653/qobject-movetothread-cannot-move-objects-with-a-parent][1]
所以我担心我的代码可能存在我尚未检测到的问题。
我修改了这部分代码,现在是:
#New slot for clicked button.
def Slot_Start_Calculation (self):
MyLongThread = QThread()
MyLongWorker = MyWorker(Qty)
MyLongWorker.moveToThread(MyLongThread)
MyLongThread.started.connect(MyLongWorker.Run_LongWorker)
MyLongWorker.WorkerFinished.connect(MyLongThread.quit)
MyLongWorker.WorkerFinished.connect(MyLongWorker.deleteLater)
MyLongThread.finished.connect(MyLongThread.deleteLater)
MyLongThread.start()
def Slot_Worker_Sent_A_Signal (self, Result):
print ("Worker sent this result: " + str(Result))
.
.
.
class MyWorker(QObject):
WorkerFinished = Signal()
CustomSignal = Signal(int)
def __init__(self, Quantity)
super().__init__()
self.Quantity = Quantity
print("Myworker's constructor")
def __del__(self):
print("Myworker's destructor")
def Run_LongWorker (self):
self.CustomSignal.connect( ??? .Slot_Worker_Sends_A_Signal)
.
.
.
self.CustomSignal.emit(MyPartialResult)
.
.
.
self.WorkerFinished.emit()
所以,现在,我真的不知道如何将此信号连接到主线程中的插槽,因为如果我没有错,则因为我更改了线程关联,所以没有父/子关系。
有人可以告诉我是否有办法做到这一点,并指导我提供有关此问题的文档?
非常感谢提前。
答案 0 :(得分:0)
最后,我想我找到了答案。在Worker类的构造函数中,我不得不更改父对象引用和父类的init调用。
class MyWorker(QObject):
WorkerFinished = Signal()
CustomSignal = Signal(int)
def __init__(self, parent = None, Quantity)
super().__init__()
self.Quantity = Quantity
print("Myworker's constructor")
def __del__(self):
print("Myworker's destructor")
def Run_LongWorker (self):
.
.
.
self.CustomSignal.emit(MyPartialResult)
.
.
.
self.WorkerFinished.emit()
现在一切都按预期进行。
如果有人看到该代码有问题,请随时告诉我。
谢谢!