PyQT5之QTimer

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

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


class ShowTime(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("动态显示当前时间")

        self.label = QLabel()
        self.startBtn = QPushButton("开始")
        self.endBtn = QPushButton("结束")

        layout = QGridLayout()
        self.timer = QTimer()
        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.setLayout(layout)

        self.startBtn.clicked.connect(self.startTimer)
        self.endBtn.clicked.connect(self.endTimer)

    def showTime(self):
        time = QDateTime.currentDateTime()
        timeDisplay = time.toString('yyyy-MM-dd hh:mm:ss dddd')
        self.label.setText(timeDisplay)

    def startTimer(self):
        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)
    p = ShowTime()
    p.show()
    sys.exit(app.exec_())

实例2

"""
让程序定时关闭
QTimer.singleShot
"""

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


if __name__ == "__main__":
    app = QApplication(sys.argv)
    label = QLabel('<font color=red size=140><b>hello world, 窗口在5庙后自动关闭!</b></font>')
    label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
    label.show()
    QTimer.singleShot(5000, app.quit)
    sys.exit(app.exec_())

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