python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyQt5 QThread类

PyQt5学习之QThread类的使用详解

作者:SongYuLong的博客

QThread是Qt线程类中最核心的底层类。要使用QThrea开始一个线程,可以创建它的一个子类,然后覆盖其QThread.run()函数。这篇文章就来和大家聊聊QThread类的使用,感兴趣的可以学习一下

PyQt5 QThread

QThread是Qt线程类中最核心的底层类。要使用QThrea开始一个线程,可以创建它的一个子类,然后覆盖其QThread.run()函数。

class Thread(QThread):
def _init_(self):
super(Thread, self)._init_()
def run(self):
# 线程相关代码
pass
thread = Thread()
thread.start()

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.setWindowTitle("QThread Demo")
        self.thread = Worker()
        self.listFile = QListWidget()
        self.btnStart = QPushButton("开始")
        layout = QGridLayout(self)
        layout.addWidget(self.listFile, 0, 0, 1, 2)
        layout.addWidget(self.btnStart, 1, 1)
        self.btnStart.clicked.connect(self.slotStart)
        self.thread.sinOut.connect(self.slotAdd)

    def slotAdd(self, file_info):
        self.listFile.addItem(file_info)

    def slotStart(self):
        self.btnStart.setEnabled(False)
        self.thread.start()



class Worker(QThread):
    sinOut = pyqtSignal(str)
    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.working = True
        self.num = 0

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        while self.working == True:
            file_str = 'File index {0}'.format(self.num)
            self.num += 1
            self.sinOut.emit(file_str)
            self.sleep(2)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWidget()
    win.show()
    sys.exit(app.exec_())

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
    
global sec
sec=0

class WorkThread(QThread):
	trigger = pyqtSignal()
	def __int__(self):
		super(WorkThread,self).__init__()

	def run(self):
		for i in range(10000000):
			pass
		
		# 循环完毕后发出信号		
		self.trigger.emit()        

def countTime():
	global  sec
	sec += 1
	# LED显示数字+1
	lcdNumber.display(sec)          

def work():
	# 计时器每秒计数
	timer.start(1000)   
	# 计时开始	
	workThread.start()       
	# 当获得循环完毕的信号时,停止计数	
	workThread.trigger.connect(timeStop)  

def timeStop():
	timer.stop()
	print("运行结束用时",lcdNumber.value())
	global sec
	sec=0

if __name__ == "__main__":  	
	app = QApplication(sys.argv) 
	top = QWidget()
	top.resize(300,120)
    
	# 垂直布局类QVBoxLayout
	layout = QVBoxLayout(top) 
    # 加个显示屏    
	lcdNumber = QLCDNumber()             
	layout.addWidget(lcdNumber)
	button = QPushButton("测试")
	layout.addWidget(button)

	timer = QTimer()
	workThread = WorkThread()

	button.clicked.connect(work)
    # 每次计时结束,触发 countTime
	timer.timeout.connect(countTime)      

	top.show()
	sys.exit(app.exec_())

事件处理processEvents

在耗时程序时不断调用QApplication.processEvents()就可以实现一边执行耗时程序,一边刷新UI页面的功能。

import sys
import time
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QListWidget, QGridLayout

class WinForm(QWidget):

    def __init__(self, parent=None):
        super(WinForm, self).__init__(parent)
        self.setWindowTitle("实时刷新页面Demo")
        self.listFile = QListWidget()
        self.btnStart = QPushButton('开始')
        layout = QGridLayout(self)
        layout.addWidget(self.listFile, 0, 0, 1, 2)
        layout.addWidget(self.btnStart, 1, 1)
        self.btnStart.clicked.connect(self.slotAdd)
        self.setLayout(layout)

    def slotAdd(self):
        for n in range(10):
            str_n = 'File index {0}'.format(n)
            self.listFile.addItem(str_n)
            QApplication.processEvents()
            time.sleep(1)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = WinForm()
    win.show()
    sys.exit(app.exec_())

到此这篇关于PyQt5学习之QThread类的使用详解的文章就介绍到这了,更多相关PyQt5 QThread类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文