我通过移动解决了我的问题mySubQThread
run()
进入myQThread
run()
也就是说,我仍然想知道为什么我之前尝试的方法不起作用。
我对线程很陌生。我遇到了这个问题,我认为我可能处理问题的方式是错误的,无论如何。我对不同的方法持开放态度,我知道这可能有点复杂。
我有一个 GUI 可以生成新的派生QThread
让我们称之为myQThread
在该线程中,我正在运行一个创建另一个线程(称为它)的进程mySubQThread
我遇到的问题如下,我在 GUI 中定义了信号,例如:signalA = QtCore.Signal(int)
和一个插槽myQThread
插槽位于mySubQThread
似乎从来没有收到信号。
这是一个工作示例。 (稍作修改)
from PySide import QtCore, QtGui
import time
class myQThread(QtCore.QThread):
myThreadSignal = QtCore.Signal(int)
def __init__(self, parent):
super(myQThread, self).__init__(parent=parent)
def run(self):
self.subThread = mySubQThread(parent=self)
self.myThreadSignal.connect(self.subThread.sub_thread_slot)
self.myThreadSignal.connect(self.test_slot)
print "starting subthread..."
self.subThread.start()
while self.subThread.isRunning():
print "myQThread is alive!"
time.sleep(1)
print "myQThread exiting run..."
@QtCore.Slot(int)
def my_thread_slot(self, a):
print "1b) Made it here!"
self.myThreadSignal.emit(a)
@QtCore.Slot(int)
def test_slot(self, a):
print "2a) Made it here!"
class mySubQThread(QtCore.QThread):
mySubSignalA = QtCore.Signal(int)
def __init__(self, parent):
super(mySubQThread, self).__init__(parent=parent)
self._abort = False
def run(self):
#Do some processing
#Wait for signal
self._abort = False
while not self._abort:
print "mySubQThread is alive!"
time.sleep(1)
print "mySubQThread exiting run..."
@QtCore.Slot(int)
def sub_thread_slot(self, a):
print "2b)Never make it here!"
self._abort = True
class myWidget(QtGui.QWidget):
myWidgetSignal = QtCore.Signal(int)
def __init__(self, parent=None):
super(myWidget, self).__init__(parent=parent)
#simple Widget to test this out....
myLayout = QtGui.QVBoxLayout()
self.runButton = QtGui.QPushButton("run")
self.runButton.clicked.connect(self.run_button_pressed)
self.otherButton = QtGui.QPushButton("other")
self.otherButton.clicked.connect(self.other_button_pressed)
myLayout.addWidget(self.runButton)
myLayout.addWidget(self.otherButton)
self.setLayout(myLayout)
@QtCore.Slot()
def run_button_pressed(self):
self.processThread = myQThread(self)
self.myWidgetSignal.connect(self.processThread.my_thread_slot)
self.myWidgetSignal.connect(self.test_slot)
self.processThread.start()
@QtCore.Slot()
def other_button_pressed(self):
self.myWidgetSignal.emit(1)
@QtCore.Slot(int)
def test_slot(self, a):
print "1a) Made it here!"
if __name__ == "__main__":
import sys
myApp = QtGui.QApplication(sys.argv)
myWin = myWidget()
myWin.show()
sys.exit(myApp.exec_())
这是一些示例输出:
请注意,如果更改该行:
self.subThread = mySubQThread(parent=self)
to
self.subThread = mySubQThread(parent=None)
它不再像示例输出中那样抱怨。两者都没有表明它能达到 2B
QObject: Cannot create children for a parent that is in a different thread.
(Parent is myQThread(0x3c3faf0), parent's thread is QThread(0x2792548), current thread is myQThread(0x3c3faf0)
starting subthread...
myQThread is alive!mySubQThread is alive!
mySubQThread is alive!
myQThread is alive!
1b) Made it here!
2a) Made it here!
1a) Made it here!