PyQT5 线程中实时刷新界面

PyQT5 多线程中实时刷新界面

1 介绍

  1. PyQT5 存在实时刷新界面的函数QApplication.processEvents(),但在线程中这个函数并不好用。
  2. 那在多线程中想实时刷新界面显示应如何操作呢?可以考虑使用QtCore.pyqtSignal()函数,这是 PyQt5 提供的自定义信号类。

2 演示

在这里插入图片描述

3 代码

1. untitled.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled3.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.
import datetime
import time
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication

class Ui_MainWindow(object):
    def __init__(self):
        self.is_pause = True
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(511, 242)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(120, 120, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(260, 120, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(130, 55, 281, 21))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(90, 60, 54, 12))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 511, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        # 链接函数
        self.pushButton.clicked.connect(self.ok_fun)  # 设置运行
        self.pushButton_2.clicked.connect(self.off_fun)  # 设置暂停、恢复


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "开始运行"))
        self.pushButton_2.setText(_translate("MainWindow", "暂停"))
        self.label.setText(_translate("MainWindow", "时间"))

    def ok_fun(self):
        self.pushButton.setStyleSheet("QPushButton{background-color:gray}")
        self.thread = Runthread()
        self.thread._signal1.connect(self.write_lineEdit)  # 1.链接自定义信号
        self.thread.start()

    def off_fun(self):
        # QApplication.processEvents()
        if self.is_pause:
            self.pushButton_2.setStyleSheet("QPushButton{background-color:lightblue}")
            self.pushButton_2.setText('恢复程序')
            self.pause_thread()
            self.is_pause=False
        else:
            self.pushButton_2.setStyleSheet("QPushButton{background-color:green}")
            self.pushButton_2.setText('暂停')
            self.resume_thread()
            self.is_pause = True

    def pause_thread(self):
        if self.thread:
            self.thread.pause()

    def resume_thread(self):
        if self.thread:
            self.thread.resume()

    def write_lineEdit(self, msg):
        self.lineEdit.setText(str(0))
        self.lineEdit.setText(msg)   # 2.将字符串写入文本框中

class Runthread(QtCore.QThread):
    _signal1 = QtCore.pyqtSignal(str)  # 3.定义信号类型是字符串
    def __init__(self):
        super(Runthread, self).__init__()
        self.is_pause=False
        self.cond=QWaitCondition()
        self.mutex=QMutex()

    def pause(self):
        self.is_pause=True

    def resume(self):
        self.is_pause=False
        self.cond.wakeAll()

    def run(self):
        self.flag = 1
        for i in range(0, 10000):
            time.sleep(0.3)
            self.mutex.lock()
            if self.is_pause:
                self.cond.wait(self.mutex)
            finish_time=datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
            self._signal1.emit(str(finish_time))  # 4.输出字符串信号值
            # 线程锁off
            self.mutex.unlock()

2. untitledMainWin.py

import sys
import untitled
from PyQt5.QtWidgets import QApplication, QMainWindow


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = untitled.Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑的小豆芽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值