qtimer在使用时多次重置计时时间
在使用 QTimer 时,我们可以使用 restart() 方法来重置计时器的时间。restart() 方法会停止计时器并将其计时时间重置为初始值,然后重新启动计时器。
下面是一个使用 QTimer 的示例,每隔一秒输出当前时间,当点击按钮时重置计时器的时间:
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QTimer, QTime
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.timer = QTimer()
self.timer.timeout.connect(self.update_time)
self.label = QLabel()
self.button = QPushButton("Reset Timer")
self.button.clicked.connect(self.reset_timer)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
self.reset_timer()
def update_time(self):
current_time = QTime.currentTime().toString("hh:mm:ss")
self.label.setText(current_time)
def reset_timer(self):
self.timer.stop()
self.timer.start(1000) # 1 second interval
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
在上面的示例中,我们创建了一个计时器 timer,并设置其超时信号连接到 update_time 方法。在 update_time 方法中,我们获取当前时间并更新标签的文本。
在 reset_timer 方法中,我们停止计时器并使用 start 方法重新启动计时器,并设置间隔为 1000 毫秒(即 1 秒)。
当点击按钮时,reset_timer 方法会被调用,计时器的时间将被重置
原文地址: https://www.cveoy.top/t/topic/irGM 著作权归作者所有。请勿转载和采集!