天天看点

PyQt5桌面应用程序之使用多线程规避程序卡死

20221214星期三:

背景:

在主类MyClass中,按钮pushButton绑定的函数,这个函数就进行页面的数据判断即可;涉及到处理逻辑问题,就重开一个函数 loadDaiBanThread ,并将这个函数丢到另一个线程中去执行;这样就避免了,点击按钮的时候,页面卡死的情况;

步骤:

1,创建多线程:执行多线程的函数:mv.loadDaiBanThread()

2,实例化多线程:并绑定到多线程执行完以后,需要执行的函数(self.get_sin_out)

3,按钮绑定到启动线程:

4,启动多线程:

5,多线程执行完以后,进行恢复操作:

1,创建多线程:执行多线程的函数:mv.loadDaiBanThread()

PyQt5桌面应用程序之使用多线程规避程序卡死

2,实例化多线程:并绑定到多线程执行完以后,需要执行的函数(self.get_sin_out)

PyQt5桌面应用程序之使用多线程规避程序卡死

3,按钮绑定到启动线程:

PyQt5桌面应用程序之使用多线程规避程序卡死

4,启动多线程:

PyQt5桌面应用程序之使用多线程规避程序卡死

5,多线程执行完以后,进行恢复操作:

PyQt5桌面应用程序之使用多线程规避程序卡死

6,成品展示:

PyQt5桌面应用程序之使用多线程规避程序卡死

另一套参考代码如下:

import json,os,sys,time
from PyQt5.QtWidgets import *  # 模块包含创造经典桌面风格的用户界面提供了一套UI元素的类
from PyDevelop.PO3_1122.Function_Gui.Fighting2022Gui.Fighting11.MainWindowZhiHui import Ui_MainWindow
from PyDevelop.PO3_1122.Function_Gui.Fighting2022Gui.Fighting11.createExcel import myExcel
from PyQt5.QtCore import Qt,QThread,pyqtSignal


class mywindow(QMainWindow,Ui_MainWindow):
    def __init__(self, *args, **kwargs):

        # 2,实例化多线程:并绑定到多线程执行完以后,需要执行的函数(self.get_sin_out)
        self.my_thread = myThread()
        # 实例化对象绑定函数 get_sin_out,当多线程执行完成以后,执行 get_sin_out 函数中的代码,即按钮的还原操作:
        self.my_thread.my_str.connect(self.get_sin_out)

        # 按钮绑定到启动线程:
        self.pushButton.clicked.connect(lambda: self.start_thread())

        '''
        构造函数,初始化参数属性
        :param args:
        :param kwargs:
        '''
        # super().__init__(*args, **kwargs)
        super(mywindow, self).__init__()
        self.setupUi(self)
        # 不允许GUI界面拉伸:
        self.setFixedSize(self.width(), self.height())  # 禁止拉伸窗口大小
        self.pushButton.setStyleSheet(
            '''QPushButton{background:#F1ABAD;border-radius:16px;}''')

    def slot1(self):
        print("slot1")
        self.pushButton.setText('程序执行中...')
        self.pushButton.setDisabled(True)
        self.pushButton.setStyleSheet('''QPushButton{background:#DFADBB;}''')

        self.lineEdit.setDisabled(True)
        print("开始执行exa02")

    # 4,启动多线程:
    def start_thread(self):
        """
        启动多线程
        :return:
        """
        try:
            print("此处省略一万行代码。")
            self.my_thread.start()
        except Exception as e:
            print(e)

    # 5,多线程执行完以后,进行恢复操作:
    def get_sin_out(self,out_str):
        if out_str == "ok":
            print("处理完成")
            # 当多线程执行完成以后,进行按钮恢复;
            self.pushButton.setText('执行')
            self.pushButton.setDisabled(False)
            self.pushButton.setStyleSheet('''QPushButton{background:#F1ABAD;border-radius:5px;}''')
            self.lineEdit.setDisabled(False)


# 1,创建多线程:继承 QThread
class myThread(QThread):
    my_str = pyqtSignal(str) # 创建任务信号
    def run(self):
        myExcel().createEXCEL()
        self.my_str.emit("ok") # 发出任务完成信号


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

           

继续阅读