PyQt6-多线程操作

记述关于PyQt6中线程的操作信息。

进行GUI设计时通常需要前端进行命令交互,然后后端进行数据处理,当数据量较多或后台操作较为费时时需要进行多线程操作,才能避免进行数据处理软件界面出现,卡死、未响应等情况。

一、线程概述

打开电脑的任务管理器,我们可以看到系统中存在很多进程,而一个进程中有存在很多个线程。

PyQt6-多线程操作_第1张图片

线程就是一个任务的处理时间线,多线程就是使用多个时间线处理多线程。

而实际上处理多线程是计算机以很块的速度在不同的线程种切换运行,人眼能够识别的速度是24帧/秒,当速度足够快时人眼无法分辨,就会造成通知进行的的错觉,这就是多线程处理的基本原理。

示例:

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

import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QProgressBar
from PyQt6.QtWidgets import QVBoxLayout
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtCore import QThread
from PyQt6.QtCore import QObject
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtCore import Qt

class CountSever(QObject):
    """线程函数"""

    _isrun = False
    countupdate = pyqtSignal()
    interval = 10
    

    def __init__(self, interval) -> None:
        """构造函数"""

        super().__init__()
        if(type(interval) == int):
            self.interval = interval

    def isrun(self,value:bool):
        self._isrun = value

    def run(self):

        while True:
            pass
            while self._isrun:
                self.countupdate.emit()
                QThread.msleep(self.interval)



class MainWindow(QMainWindow):
    """进度条主界面"""

    countstart = pyqtSignal(bool)

    def __init__(self) -> None:
        """构造函数"""

        super().__init__()
        self.init_ui()
        self.setcenter()


    def init_ui(self):
        """初始化ui界面"""

        self.setWindowTitle("线程刷新进度条")
        self.resize(400, 300)

        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)
        self.main_layout = QVBoxLayout()
        self.main_layout.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        self.main_widget.setLayout(self.main_layout)

        self.progress_1 = QProgressBar(self)
        self.progress_1.setRange(0,100)
        self.main_layout.addWidget(self.progress_1)
        self.progress_2 = QProgressBar(self)
        self.progress_2.setRange(0,100)
        self.main_layout.addWidget(self.progress_2)
        self.main_layout.addStretch(1)
        self.progress_3 = QProgressBar(self)
        self.progress_3.setRange(0, 100)
        self.main_layout.addWidget(self.progress_3)
        self.progress_4 = QProgressBar(self)
        self.progress_4.setRange(0, 100)
        self.main_layout.addWidget(self.progress_4)

        self.btn_start = QPushButton("Start")
        self.btn_start.setFixedSize(120,30)
        self.btn_start.clicked.connect(self.start)
        self.main_layout.addWidget(self.btn_start)
        self.main_layout.setAlignment(self.btn_start,Qt.AlignmentFlag.AlignCenter)
        
        # thread
        self.cs1 = CountSever(100)
        self.cs1.countupdate.connect(self.countupdate)
        self.countstart.connect(self.cs1.isrun)
        self.th1 = QThread()
        self.cs1.moveToThread(self.th1)
        self.th1.started.connect(self.cs1.run)
        self.th1.start()

        self.cs2 = CountSever(150)
        self.cs2.countupdate.connect(self.countupdate)
        self.countstart.connect(self.cs2.isrun)
        self.th2 = QThread()
        self.cs2.moveToThread(self.th2)
        self.th2.started.connect(self.cs2.run)
        self.th2.start()

        self.cs3 = CountSever(1000)
        self.cs3.countupdate.connect(self.countupdate)
        self.countstart.connect(self.cs3.isrun)
        self.th3 = QThread()
        self.cs3.moveToThread(self.th3)
        self.th3.started.connect(self.cs3.run)
        self.th3.start()

        self.cs4 = CountSever(1500)
        self.cs4.countupdate.connect(self.countupdate)
        self.countstart.connect(self.cs4.isrun)
        self.th4 = QThread()
        self.cs4.moveToThread(self.th4)
        self.th4.started.connect(self.cs4.run)
        self.th4.start()

    def setcenter(self):
        """界面居中显示"""

        win_rect = self.frameGeometry()
        screen_center = self.screen().availableGeometry().center()
        win_rect.moveCenter(screen_center)
        self.move(win_rect.topLeft())


    def start(self):
        if self.btn_start.text() == "Start":
            self.countstart.emit(True)
            self.btn_start.setText("Pause")
        elif self.btn_start.text() == "Pause":
            self.countstart.emit(False)
            self.btn_start.setText("Start")

    def countupdate(self):
        if self.sender() == self.cs1:
            self.progress_1.setValue(self.progress_1.value() + 1)
        elif self.sender() == self.cs2:
            self.progress_2.setValue(self.progress_2.value() + 1)
        elif self.sender() == self.cs3:
            self.progress_3.setValue(self.progress_3.value() + 1)
        elif self.sender() == self.cs4:
            self.progress_4.setValue(self.progress_4.value() + 1)


if __name__ == "__main__":
    """ 主程序运行 """

    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec())


    
PyQt6-多线程操作_第2张图片

二、使用QObject类实现线程操作

创建继承自QObject类的线程处理类,编写run()函数,然后通过信号和槽进行线程间的注意事项调用。

model:

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

import sys
import time

from PyQt6.QtCore import QObject,pyqtSignal

class ClockServer(QObject):
    """Clock server"""

    update_time = pyqtSignal(str)       # 时间更新信号
    __isrun = False                     # Running flag. 

    @property
    def isrun(self):
        """get run flag."""
        return self.__isrun

    @isrun.setter
    def isrun(self,value):
        """set run flag."""
        if type(value) is bool:
            self.__isrun = value

    def run(self):
        """start server"""
        while True:
            start_time = time.time()
            while self.isrun:
                self.update_time.emit("{0:.2f}".format(time.time()-start_time))
                time.sleep(0.01)

view

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


from PyQt6.QtWidgets import QWidget,QLCDNumber,QPushButton,QVBoxLayout
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt


class StopWatchView(QWidget):
    """
    秒表构造函数
    """

    def __init__(self):
        """
        构造函数
        """

        super().__init__()

        self.setWindowTitle("Stop Watch")
        self.setWindowIcon(QIcon(r"res/time04.ico"))
        
        self.initUI()

    def initUI(self):
        """
        初始化界面
        """

        # Set window location and size.
        self.setGeometry(400,300,300,200)

        # 显示时间
        self.lcd = QLCDNumber()
        self.lcd.setDigitCount(6)
        self.lcd.display('0.00')

        # Show button.
        self.btn = QPushButton('Start')
        self.btn.setStyleSheet('background-color:darkgray')

        # Set layout.
        vboxlayout = QVBoxLayout()
        self.setLayout(vboxlayout)

        vboxlayout.addWidget(self.lcd)
        vboxlayout.addSpacing(5)
        vboxlayout.addWidget(self.btn)

controller:

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

import sys

from model.clockutil import ClockServer
from view.stopwatchview import StopWatchView
from PyQt6.QtCore import Qt,QThread

class StopWatchController:
    """View controller"""
    def __init__(self):
        self.view = StopWatchView()
        self.view.btn.clicked.connect(self.btn_onclick)
        self.view.show()

        self.timeserver = ClockServer()
        self.timeserver.update_time.connect(self.view.lcd.display)
        
        # 注意,创建线程时,需要给线程变量添加self标识,否则线程将会异常,甚至无法正常启动线程
        # 初步猜测应该是因为没有self标识,创建的就只是局部变量,而不是类的实例属性,无法跨线程使用。
        self.thread = QThread()
        self.timeserver.moveToThread(self.thread)
        self.thread.started.connect(self.timeserver.run)
        self.thread.start()

    def btn_onclick(self):
        """按键响应事件"""
        if self.view.btn.text() == "Start":
            self.timeserver.isrun = True
            self.view.btn.setText("Stop")
        else:
            self.timeserver.isrun = False
            self.view.btn.setText("Start")

mian:

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

import sys

from controller.stopwatchcontroller import StopWatchController
from PyQt6.QtWidgets import QApplication


if __name__ == "__main__":
    """main"""
    app = QApplication(sys.argv)
    stopwatch = StopWatchController()
    
    sys.exit(app.exec())

结果:

PyQt6-多线程操作_第3张图片

你可能感兴趣的:(#,PyQt,PyQt,python,线程)