PyQt5进阶(二)——多线程:QTimer

应用程序开发中多线程的必要性:

一般情况下,应用程序都是单线程运行的,但是对GUI程序来说,单线程有时候满足不了要求,但是对于一些特殊情况:比如一个耗时较长的操作,运行过程会有卡顿让用户以为程序出错而把程序关闭或是系统本身认为程序运行出错而自动关闭程序。这个时候就需要用到多线程的知识。一般来说,多线程技术主要涉及以下三种方法:

1.利用计时器模块QTimer

2.使用多线程模块QThread

3.使用事件处理功能

QTimer

如果要在应用程序中周期性地进行某项操作,就需要用到QTimer(定时器),QTimer类中的常用方法如下所示:

方法 描述
start(milliseconds) 启动或重新启动定时器,时间间隔单位为毫秒
stop() 停止定时器

QTimer类中的常用信号如下所示:

信号 描述
singleShot 在给定的时间间隔后调用一个槽函数时发射此信号
timeout 当定时器超时时发射此信号

示例一:显示时间(timeout信号)

from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QListWidget, QGridLayout, QLabel
from PyQt5.QtCore import QTimer, QDateTime
import sys


class WinForm(QWidget):

    def __init__(self, parent=None):
        super(WinForm, self).__init__(parent)

        self.setWindowTitle("QTimer demo")
        self.label = QLabel('显示当前时间')
        self.startBtn = QPushButton('开始')
        self.endBtn = QPushButton('结束')

        layout = QGridLayout(self)

        # 初始化一个定时器
        self.timer = QTimer(self)
        # 将定时器超时信号与槽函数showTime()连接
        self.timer.timeout.connect(self.showTime)

        layout.addWidget(self.label, 0, 0, 1, 2)
        layout.addWidget(self.startBtn, 1, 0)
        layout.addWidget(self.endBtn, 1, 1)

        # 连接按键操作和槽函数
        self.startBtn.clicked.connect(self.startTimer)
        self.endBtn.clicked.connect(self.endTimer)

        self.setLayout(layout)

    def showTime(self):
        # 获取系统现在的时间
        time = QDateTime.currentDateTime()
        # 设置系统时间显示格式
        timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd")
        # 在标签上显示时间
        self.label.setText(timeDisplay)

    def startTimer(self):
        # 设置计时间隔并启动,每隔1000毫秒(1秒)发送一次超时信号,循环进行
        self.timer.start(1000)
        self.startBtn.setEnabled(False)
        self.endBtn.setEnabled(True)

    def endTimer(self):
        self.timer.stop()
        self.startBtn.setEnabled(True)
        self.endBtn.setEnabled(False)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = WinForm()
    form.show()
    sys.exit(app.exec_())

示例二:窗口自动消失(singleShot信号)

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

if __name__ == '__main__':
    app = QApplication(sys.argv)
    label = QLabel("<font color=red size=128><b>Hello PyQT,窗口会在5秒后消失!</b></font>")

    # 无边框窗口
    label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)

    label.show()

    # 设置5s后自动退出
    QTimer.singleShot(5000, app.quit)

    sys.exit(app.exec_())

接下篇…

--------------------- 本文来自 知诸狭 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_34710142/article/details/80913448?utm_source=copy

猜你喜欢

转载自blog.csdn.net/IAlexanderI/article/details/82946669
今日推荐