我有一个对话框,显示正在运行的线程的进度:
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
from PyQt5.QtCore import *
class LoaderProgress(QDialog):
def __init__(self, parent=None):
super(LoaderProgress, self).__init__(parent)
loadUi("CliReportsUI/loaderprogress.ui", self)
self.pbLoader.setValue(0)
self.btn_cancel.clicked.connect(self.killthread)
def watchthread(self,worker):
self.thread = worker(self)
self.thread.totsignal.connect(self.pbLoader.setMaximum)
self.thread.cntsignal.connect(self.updateprogress)
self.thread.finished.connect(self.close)
def settitle(self,title):
self.setWindowTitle(title)
def startthread(self):
self.thread.start()
def updateprogress(self,n):
self.pbLoader.setValue(n)
def killthread(self):
print('How do I do this')
另一个类中的方法以以下方式运行线程:
dlg = LoaderProgress(self)
dlg.watchthread(FileLoader)
dlg.settitle("Loading The Master File...")
dlg.show()
dlg.startthread()
然后是worker类:
class FileLoader(QThread):
totsignal = pyqtSignal(int)
cntsignal = pyqtSignal(int)
def __init__(self,parent=None):
super(FileLoader, self).__init__(parent)
self.threadactive = True
self.total = 100
def run(self):
self.totsignal.emit(self.total)
i = 1
while(i < self.total and self.threadactive):
print(time.time)
if(time.time() % 1==0):
i+=1
self.cntsignal.emit(i)
在加载程序对话框中,我有一个按钮将取消进程(btn_cancel),但是如果单击取消按钮,我不知道如何终止正在运行的线程。感谢您的协助。
答案 0 :(得分:3)
您必须实现一种stop()
方法,该方法将threadactive
标志更改为False
,并等待带有wait()
的项
class FileLoader(QThread):
totsignal = pyqtSignal(int)
cntsignal = pyqtSignal(int)
def __init__(self,parent=None):
super(FileLoader, self).__init__(parent)
self.threadactive = True
self.total = 100
def run(self):
self.totsignal.emit(self.total)
i = 1
while(i < self.total and self.threadactive):
print(time.time())
if(time.time() % 1==0):
i+=1
self.cntsignal.emit(i)
def stop(self):
self.threadactive = False
self.wait()
然后使用killthread
方法调用它:
def killthread(self):
self.thread.stop()
print('How do I do this')