溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PyQt5 movetothread進程啟動失效解決辦法

發(fā)布時間:2020-05-26 14:59:00 來源:億速云 閱讀:624 作者:鴿子 欄目:編程語言

定義了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('正在讀取目錄數(shù)據(jù)')
elif self.url is not None:
if self.type == 'second':
data = self.scy.getChildPage(self.url)
self.addSignal.emit('正在讀取次級目錄數(shù)據(jù)')
elif self.type == 'three':
data = self.scy.getMagzineList(self.url)
self.addSignal.emit('正在讀取文章目錄數(shù)據(jù)')
else:
self.addSignal.emit('傳入數(shù)據(jù)不正確,請修改后重試')
return
for item in data:
self.addSignal.emit('正在在顯示目錄插入數(shù)據(jù)')
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)

但是在點擊按鈕之后,沒有反應(yīng),后經(jīng)過debug,發(fā)現(xiàn)能運行到線程中,但是該運行線程的run函數(shù)的時候就沒動靜了。
我懷疑是在按鈕函數(shù)運行完后將線程變量被銷毀了?后經(jīng)過實驗,添加下面兩行代碼即可正常運行,即將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)

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI