pyqt6实现QTimer定时器介绍和使用场景

来自:网络
时间:2024-03-18
阅读:

QTimer定时器介绍

PyQt6中的QTimer是一个定时器类,用于在指定的时间间隔内执行某个操作。QTimer提供了一种简单的方法来实现定时任务,例如自动更新界面、动画效果等。

函数原型:

from PyQt6.QtCore import QTimer

QTimer()

创建一个QTimer对象:

timer = QTimer()

设置定时器的超时时间(毫秒):

timer.setInterval(1000)  # 设置为1000毫秒(1秒)

连接定时器的超时信号到槽函数:

def on_timeout():
    print("定时器超时")

timer.timeout.connect(on_timeout)

启动定时器:

timer.start()

停止定时器:

timer.stop()

使用案例

每隔1秒更新界面上的文本

from PyQt6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PyQt6.QtCore import QTimer
import sys


class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("Hello, World!")
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        self.setLayout(layout)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_text)
        self.timer.start(1000)  # 每隔1秒触发一次timeout信号
        self.cnt = 1

    def update_text(self):
        self.label.setText(f"Hello, PyQt6! cnt:{self.cnt}")
        self.cnt = self.cnt + 1


app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec())

代码中使用了QTimer类来实现定时器功能。首先,创建了一个MyApp类,继承自QWidget类。在MyApp类的构造函数中,创建了一个QLabel对象和一个QVBoxLayout对象,并将它们添加到布局中。然后,创建了一个QTimer对象,并将其timeout信号连接到update_text槽函数。最后,启动了定时器,并设置了时间间隔为1000毫秒(即1秒)。

在update_text槽函数中,更新了QLabel对象的文本,并将计数器cnt加1。这样,每次调用update_text函数时,都会更新窗口中的文本,并使计数器cnt递增。

最后,创建了一个QApplication对象和一个MyApp对象,并将MyApp对象显示出来。程序运行结束后,退出应用程序。

10秒后显示一个消息框 

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox
from PyQt6.QtCore import QTimer


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

        # 创建一个QTimer对象
        self.timer = QTimer()
        # 将timeout信号连接到自定义的槽函数
        self.timer.timeout.connect(self.on_timeout)
        # 设置定时器的时间间隔为10000毫秒(10秒)
        self.timer.setInterval(10000)
        self.timer.start()

    def on_timeout(self):
        # 当定时器超时时,显示一个消息框
        QMessageBox.information(self, 'Timeout', '10秒已过!')
        self.timer.stop()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())

在这个示例中,我们首先导入了所需的库,并创建了一个名为Example的QWidget子类。在initUI方法中,我们设置了窗口的大小、标题和位置,并创建了一个QTimer对象。然后,我们将QTimer的timeout信号连接到自定义的on_timeout槽函数,并设置定时器的时间间隔为10000毫秒(10秒)。最后,我们在on_timeout槽函数中显示一个消息框,通知用户已经过了10秒,并停止定时器。

返回顶部
顶部