| 方法 | 描述 |
|---|---|
| start(milliseconds) | 啟動或重新啟動定時器,時間間隔為毫秒。如果定時器已經運行,它將被停止并重新啟動。如果singleShot信號為真,定時器將僅被激活一次 |
| Stop() | 停止定時器 |
| 信號 | 描述 |
|---|---|
| singleShot | 在給定的時間間隔后調用一個槽函數時發射此信號 |
| timeout | 當定時器超時時發射此信號 |
示例1:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QWidget):
count = 0
def __init__(self):
super().__init__()
self.setGeometry(100, 50, 500, 400)
self.setWindowTitle('QTimer')
self.list = QListWidget()
self.label = QLabel('顯示當前時間')
self.start = QPushButton('開始')
self.end = QPushButton('結束')
layout = QGridLayout()
#初始化定時器
self.timer = QTimer(self)
self.timer.timeout.connect(self.showTime)
self.start.clicked.connect(self.startTimer)
self.end.clicked.connect(self.endTimer)
layout.addWidget(self.label,0,0,1,2)
layout.addWidget(self.start,1,0)
layout.addWidget(self.end,1,1)
self.setLayout(layout)
def showTime(self):
#獲取系統現在的時間
time = QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd')
self.label.setText(time)
def startTimer(self):
#設置時間間隔并啟動定時器
self.timer.start(1000)
self.start.setEnabled(False)
self.end.setEnabled(True)
def endTimer(self):
#關閉定時器
self.timer.stop()
self.start.setEnabled(True)
self.end.setEnabled(False)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
運行效果如下:

示例2:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
if __name__ == "__main__":
app = QApplication(sys.argv)
label = QLabel('font color=blue size=20>b>PyQt5,窗口5秒后消失/b>/font>')
#無邊框窗口
label.setWindowFlags(Qt.SplashScreen|Qt.FramelessWindowHint)
label.show()
#設置5秒后自動退出
QTimer.singleShot(5000,app.quit)
sys.exit(app.exec_())
運行效果如下:

我正在使用python創建程序,并且正在使用pyqt。我目前正在使用QTimer,我想每秒鐘打印一次“ timer works”,并在5秒鐘后停止打印。這是我的代碼:
timers = []
def thread_func():
print("Thread works")
timer = QtCore.QTimer()
timer.timeout.connect(timer_func)
timer.start(1000)
print(timer.remainingTime())
print(timer.isActive())
timers.append(timer)
def timer_func():
print("Timer works")
解決方案
以下是一個簡單的演示,顯示了如何創建在固定數量的超時后停止計時的計時器。
from PyQt5 import QtCore
def start_timer(slot, count=1, interval=1000):
counter = 0
def handler():
nonlocal counter
counter += 1
slot(counter)
if counter >= count:
timer.stop()
timer.deleteLater()
timer = QtCore.QTimer()
timer.timeout.connect(handler)
timer.start(interval)
def timer_func(count):
print('Timer:', count)
if count >= 5:
QtCore.QCoreApplication.quit()
app = QtCore.QCoreApplication([])
start_timer(timer_func, 5)
app.exec_()
到此這篇關于PyQt5中QTimer定時器的實例代碼的文章就介紹到這了,更多相關PyQt5 QTimer定時器內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!