PyQt5 movetothread 啓動進程後失效問題

定義了work類:

class AddWork(QObject):
addSignal = pyqtSignal(str)

def __init__(self, parentItem, type, url=None):
super(AddWork, self).__init__()
# super().__init__()
self.type = type
self.parentItem = parentItem
self.scy = scrpy()
self.url = url

def work(self):
print('1')
if self.type == 'top':
data = self.scy.getIndex()
self.addSignal.emit('正在讀取目錄數據')
elif self.url is not None:
if self.type == 'second':
data = self.scy.getChildPage(self.url)
self.addSignal.emit('正在讀取次級目錄數據')
elif self.type == 'three':
data = self.scy.getMagzineList(self.url)
self.addSignal.emit('正在讀取文章目錄數據')
else:
self.addSignal.emit('傳入數據不正確,請修改後重試')
return
for item in data:
self.addSignal.emit('正在在顯示目錄插入數據')
node = QTreeWidgetItem(self.parentItem)
node.setText(0, item[0])
node.setText(1, item[1])
self.addSignal.emit('顯示完成')

在主程序中使用:
def ButtonReadData(self):
if self.rootNode.childCount() != 0:
return
worker = AddWork(self.rootNode, 'top')
worker.addSignal.connect(self.ShowLog)

thread = QThread()
print('ready start button thread')
thread.start()
print('end start button thread')
worker.moveToThread(thread)
thread.started.connect(worker.work)

但是在點擊按鈕之後,沒有反應,後經過debug,發現能運行到線程中,但是該運行線程的run函數的時候就沒動靜了。
我懷疑是在按鈕函數運行完後將線程變量被銷燬了?後經過實驗,添加下面兩行代碼即可正常運行,即將work和線程添加到一個全局的列表中保存:

self.threadList.append(thread)
self.workers.append(worker)

總的按鈕事件代碼爲:

def ButtonReadData(self):
if self.rootNode.childCount() != 0:
return
worker = AddWork(self.rootNode, 'top')
worker.addSignal.connect(self.ShowLog)

thread = QThread()
print('ready start button thread')
thread.start()
print('end start button thread')
worker.moveToThread(thread)
thread.started.connect(worker.work)

self.threadList.append(thread)
self.workers.append(worker)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章