参考资料:哔哩哔哩 pyqt5 thread多线程示例
以下代码来自该视频,我自己手动实现了一下,当作一个模板来学习,欢迎大家一起学习。
运行示例
三个进程同时执行,并且可以单独控制暂停和继续执行。
以下给出运行代码:文章来源:https://www.toymoban.com/news/detail-577534.html
from PyQt5 import QtCore,QtWidgets,QtGui
from PyQt5 import uic
import sys,time
class THREAD_APP(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = uic.loadUi('thread.ui',self)
self.thread={}
self.pushButton.clicked.connect(self.start_worker_1)
self.pushButton_2.clicked.connect(self.start_worker_2)
self.pushButton_3.clicked.connect(self.start_worker_3)
self.pushButton_4.clicked.connect(self.stop_worker_1)
self.pushButton_5.clicked.connect(self.stop_worker_2)
self.pushButton_6.clicked.connect(self.stop_worker_3)
def start_worker_1(self):
self.thread[1] = ThreadClass(parent=None,index=1)
self.thread[1].start()
self.thread[1].any_signal.connect(self.my_function)
self.pushButton.setEnabled(False)
def start_worker_2(self):
self.thread[2] = ThreadClass(parent=None, index=2)
self.thread[2].start()
self.thread[2].any_signal.connect(self.my_function)
self.pushButton_2.setEnabled(False)
def start_worker_3(self):
self.thread[3] = ThreadClass(parent=None,index=3)
self.thread[3].start()
self.thread[3].any_signal.connect(self.my_function)
self.pushButton_3.setEnabled(False)
def stop_worker_1(self):
self.thread[1].stop()
self.pushButton.setEnabled(True)
def stop_worker_2(self):
self.thread[2].stop()
self.pushButton_2.setEnabled(True)
def stop_worker_3(self):
self.thread[3].stop()
self.pushButton_3.setEnabled(True)
def my_function(self,counter):
cnt = counter
index = self.sender().index
if index == 1:
self.progressBar.setValue(cnt)
if index == 2:
self.progressBar_2.setValue(cnt)
if index == 3:
self.progressBar_3.setValue(cnt)
class ThreadClass(QtCore.QThread):
any_signal = QtCore.pyqtSignal(int)
def __init__(self,parent=None,index=0):
super(ThreadClass,self).__init__(parent)
self.index = index
self.is_running = True
def run(self):
print('Starting thread...',self.index)
cnt=0
while(True):
cnt+=1
if cnt==99: cnt=0
time.sleep(0.01)
self.any_signal.emit(cnt)
def stop(self):
self.is_running=False
print('stopping thread...',self.index)
self.terminate()
app=QtWidgets.QApplication(sys.argv)
mainWindow = THREAD_APP()
mainWindow.show()
sys.exit(app.exec_())
完整程序参考:PyQt5 多线程执行和停止示例文章来源地址https://www.toymoban.com/news/detail-577534.html
到了这里,关于PyQt5多线程的执行和停止的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!