PySide6 GUI 编程(16):QTimer 的简单用法

2024-07-25 16:05:06 浏览数 (1)

延时后一次执行

示例代码

代码语言:python代码运行次数:0复制
import sys
from datetime import datetime

from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QVBoxLayout, QWidget


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QTimer Example')

        self.button = QPushButton('START SINGLE-SHOT')
        self.button.clicked.connect(self.init_label)

        self.label = QLabel(f'Hello, PySide6! {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
        self.label.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.label)

        container = QWidget()
        container.setLayout(self.layout)

        self.setCentralWidget(container)

        self.trigger_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.delay_time = 2000
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)

    def update_time(self):
        self.label.setText(f'Trigger@{self.trigger_time}nSingleShot@{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
        self.button.setCheckable(True)
        self.button.setHidden(False)

    def init_label(self):
        self.label.setText(f'wait {self.delay_time} milli-seconds')
        self.button.setCheckable(False)
        self.button.setHidden(True)
        self.trigger_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 设置延时时间与触发的槽函数
        self.timer.singleShot(self.delay_time, self.update_time)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

运行效果

定时器延时一次执行定时器延时一次执行

定时器周期性执行

示例代码

代码语言:python代码运行次数:0复制
import sys
from datetime import datetime

from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QApplication, QLabel, QLineEdit, QMainWindow, QPushButton, QVBoxLayout, QWidget


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('QTimer Example')

        self.input_line = QLineEdit()
        self.input_line.setPlaceholderText('请输入定时器级间隔周期,单位为秒,如 1 代表每隔 1 秒运行一次')
        self.input_line.returnPressed.connect(self.check_input)

        self.push_button = QPushButton('停止定时器')
        self.push_button.clicked.connect(self.end_timer)

        self.label = QLabel('Hello, PySide6 QTimer!')
        self.label.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)
        self.wait_timer_label = QLabel('Wait To Start')
        self.wait_timer_label.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.input_line)
        self.layout.addWidget(self.push_button)
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.wait_timer_label)

        container = QWidget()
        container.setLayout(self.layout)

        self.trigger_count = 0
        self.wait_second_count = 0

        self.wait_timer = QTimer()
        self.wait_timer.timeout.connect(self.wait_to_start)
        self.wait_timer.setInterval(1000)  # 默认每秒执行一次

        self.setCentralWidget(container)

    def wait_to_start(self):
        self.wait_timer_label.setText(f'等待 {self.wait_second_count} 秒')
        if self.wait_second_count <= 0:
            self.update_time()
            self.wait_second_count = int(self.input_line.text()) - 1
            return
        self.wait_second_count -= 1

    def check_input(self):
        input_interval = self.input_line.text()
        if not str.isalnum(input_interval):
            self.label.setText(f'非法的间隔周期:{input_interval}, 请输入整数')
        else:
            internal = int(input_interval)
            if internal <= 0 or internal > 5:
                self.label.setText(f'非法的间隔周期:{input_interval}, 合法范围:[1, 5]')
            else:
                self.input_line.setReadOnly(True)
                self.input_line.setDisabled(True)
                self.wait_second_count = int(self.input_line.text()) - 1
                self.push_button.setEnabled(True)
                self.wait_timer.start()  # 等待定时器开始工作

    # 定时器触发
    def update_time(self):
        self.trigger_count  = 1
        self.label.setText(f'定时器第{self.trigger_count}次触发@{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')

    # 停止定时器
    def end_timer(self):
        self.wait_timer.stop()
        self.wait_second_count = 0
        self.input_line.setReadOnly(False)
        self.input_line.setEnabled(True)
        self.trigger_count = 0
        self.label.setText(f'定时器停止时间@{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
        self.wait_timer_label.setText(f'Wait To Start')
        self.push_button.setDisabled(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

运行效果

定时器周期性运行定时器周期性运行

0 人点赞