欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

PyQt5系列教程(十二)QThread使用

PyQt5开发 迷途小书童 4年前 (2020-04-22) 5461次浏览 0个评论

软硬件环境

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

视频看这里

此处是youtube的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。

简介

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

源码下载

https://github.com/xugaoxiang/learningPyQt5

喜欢 (0)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.