PyQt5中的QThread

187 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

软硬件环境

  • Windows 10 64bit
  • Anaconda3 with python 3.7
  • PyCharm 2019.3
  • PyQt5

简介

QThreadQt线程类中最核心的底层类。要使用QThread开始一个线程,必须创建一个QThread的子类,然后重写QThread.run方法。在使用线程时,可以直接得到Thread实例,调用其start()方法即可启动线程。

一般来讲,业务的线程任务就放在run方法中,当run退出之后,线程就结束了。QThreadstartedfinished信号,可以为这两个信号绑定相应的槽函数,在线程启动启动和结束时执行一些代码来记性资源的初始化和释放的动作。

qthread

实例

使用designer.exe制作UI界面,一个label和一个pushbutton,并且使用水平布局,如下

qthread

将界面保存成qthread.ui文件,然后利用pyuic5.exe生成python代码

pyuic5.exe -o ui_mainwindow.py qthread.ui

首先来到工程的入口函数main.py,初始化app并进入事件循环

import sys

from PyQt5.QtWidgets import QApplication

from gui.mainwindow import MainWindow

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

我们着重看下mainwindow.py

import time

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import QThread, pyqtSignal
from .ui_mainwindow import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        
        self.thread = Worker()
        self.thread.sig.connect(self.updateLabel)
        
        self.pushButton.clicked.connect(self.buttonClicked)
    
    def buttonClicked(self):
        self.thread.start()
    
    def updateLabel(self, text):
        self.label.setText(text)


class Worker(QThread):
    sig = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.count = 0
    
    def run(self):
        
        while True:
            time.sleep(1)
            self.count += 1
            if (self.count % 5 == 0):
                self.sig.emit(f"已执行{self.count}秒")

可以看到,我们定义了一个Worker,继承自QThread,并且实现了run()方法,使用time.sleep来模拟耗时操作,当计数器count对5来取余为0时,发送信号sig,更新label的文本。

运行下工程

qthread

源码下载

github.com/xugaoxiang/…