是否有重设单热计时器的意愿?我将singleShot计时器设置为5000 so,并希望通过单击按钮来重置计时器,以便计时器再次开始计数。
from PyQt5 import QtCore from PyQt5.QtCore import QTimer from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QPushButton, QFrame, QLabel, QWidget import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.centralWidget = QWidget() self.mainLayout = QHBoxLayout() self.centralWidget.setLayout(self.mainLayout) self.setCentralWidget(self.centralWidget) self.mainFrame = QFrame(self.centralWidget) self.mainFrame.setContentsMargins(0,0,0,0) self.mainLayout.addWidget(self.mainFrame) self.vLay = QVBoxLayout(self.mainFrame) self.button = QPushButton() self.button.setText('press me') self.button2 = QPushButton() self.button2.setText('Stop') self.label = QLabel(self.mainFrame) self.label.setText('testLabel') self.vLay.addWidget(self.button) self.vLay.addWidget(self.button2) self.vLay.addWidget(self.label) self.timer = QTimer() self.timer.singleShot(5000, self.shot) self.label.setText('running') self.button.clicked.connect(self.resetTimer) self.button2.clicked.connect(self.stopTimer) def resetTimer(self): self.label.setText('reseted') self.timer = QTimer() self.timer.singleShot(5000, self.shot) def stopTimer(self): self.timer.stop() self.label.setText('stopped') def shot(self): self.label.setText('shot') if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
如果我按下resetButton,似乎会初始化一个新计时器,但我希望重置当前计时器。
发布于 2022-06-21 16:01:39
QTimer.singleShot() 是一个静态函数,它创建了一个新的单次定时器。
QTimer.singleShot()
实际上,您并没有使用您创建的QTimer实例,实际上,每次调用该函数时都会创建一个新的计时器。
您必须在 singleShot 实例上设置QTimer属性,将其连接到所需的插槽,并启动该定时器:
singleShot
class MainWindow(QMainWindow): def __init__(self): # ... self.timer = QTimer() self.timer.setSingleShot(True) self.timer.setInterval(5000) self.timer.timeout.connect(self.shot) self.timer.start() def resetTimer(self): if self.timer.isActive(): self.label.setText('reset') else: