QTimer - stopery
15 December 2008
Comments
Klasa QTimer umożliwia tworzenie "stoperów" ciągłych jak i jednokrotnych. Za ich pomocą aplikacje mogą wykonywać określone czynności po upływie określonego czasu. Przykład stopera ciągłego jak i jednokrotnego przedstawia poniższy przykład:
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from timer import Ui_MainWindow
class timers(QtGui.QMainWindow):
def __init__(self, parent=None):
super(timers, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ctimer = QtCore.QTimer()
self.stimer = QtCore.QTimer()
#buttons
QtCore.QObject.connect(self.ui.constant,QtCore.SIGNAL("clicked()"), self.constant)
QtCore.QObject.connect(self.ui.single,QtCore.SIGNAL("clicked()"), self.single)
# constant timer
QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate)
QtCore.QMetaObject.connectSlotsByName(self)
def constant(self):
"""
Start the constant timer
"""
self.ctimer.start(1000)
def constantUpdate(self):
"""
slot for constant timer timeout
"""
val = self.ui.constantProgress.value() + 10
if val > 100:
val = 0
self.ui.constantProgress.setValue(val)
def single(self):
"""
run singleShot timer after button push
"""
self.stimer.singleShot(1000, self.singleUpdate)
def singleUpdate(self):
"""
Slot for singleShot timer timeout
"""
val = self.ui.singleProgress.value() + 10
if val > 100:
val = 0
self.ui.singleProgress.setValue(val)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = timers()
myapp.show()
sys.exit(app.exec_())

Uruchomienie ciągłego stopera spowoduje że co sekundę (1000 milisekund) stan paska postępu QProgressBar będzie wzrastał o 10%. W przypadku stopera jednokrotnego (singleShot) po sekundzie od kliknięcia nastąpi zwiększenie wartości paska postępu (tylko raz). Stopery ciągłe wykorzystują mechanizm sygnałów i slotów - emitując sygnał timeout(). Stopery jednokrotne tworzone są za pomocą metody singleShot(czas, odbiornik), gdzie odbiornikiem jest nazwa metody naszej klasy, która zostanie wykonana po upływie podanego czasu.
Gotowy skryp dostępny jest do pobrania.
RkBlog
Comment article