定義了work類:node
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)app
總的按鈕事件代碼爲:ide
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)函數