PyQT5之QThread

"""
动态显示当前时间
QTimer
QThread
"""

from PyQt5.QtWidgets import QWidget, QMessageBox, QVBoxLayout, QPushButton, QLCDNumber, QApplication, QListWidget, QGridLayout, QLabel
from PyQt5.QtCore import QTimer, QDateTime, QThread, pyqtSignal
import sys

sec = 0


class WorkThread(QThread):
    timer = pyqtSignal()   # 每隔一秒发送一次信号
    end = pyqtSignal()     # 计数完成后发送一次信号

    def run(self):
        while True:
            self.sleep(1)  # 休眠1秒
            if sec == 5:
                self.end.emit()
                break
            self.timer.emit()


class Counter(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("动态显示当前时间")
        self.resize(300, 300)
        button = QPushButton("开始计数")

        layout = QVBoxLayout()
        self.lcdNumber = QLCDNumber()

        layout.addWidget(self.lcdNumber)
        layout.addWidget(button)
        self.setLayout(layout)

        self.workThread = WorkThread()

        self.workThread.timer.connect(self.countTime)
        self.workThread.end.connect(self.end)
        button.clicked.connect(self.work)

    def countTime(self):
        global sec
        sec += 1
        self.lcdNumber.display(sec)

    def end(self):
        QMessageBox.information(self, "消息", "计数结束", QMessageBox.Ok)

    def work(self):
        self.workThread.start()


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


posted @ 2024-06-14 16:48  星空28  阅读(8)  评论(0编辑  收藏  举报