定义了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)
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。