I'm trying to run multiple timers in a parallel manner using PyQt's QTimer objects. I'm trying to define an arbitrary number of timers (defined by n), and to launch them all at the same time : however, they'd all have different intervals (or timeouts), and these intervals would be different each time they'd start.
As of now, my test code looks like this :
from PyQt5 import QtCore, QtWidgets
import random
# Fixes an arbitrary number of timers and indicators
n = random.randint(5, 20)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
# Initializes empty lists of labels and timers
self.indicators = []
self.clocks = []
# Loops the initialization of each label/timer duo
for i in range(0, n):
id = i
# Creates a label to have a feedback on the timer's behaviour
self.indicators.append(QtWidgets.QLabel("Time1 :"))
self.indicators[id].id = id
# Creates a basic layout
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.indicators[i])
# Creates the n°ID timer
self.clocks.append(QtCore.QTimer())
self.clocks[id].id = id
# Sets it so singleshot mode,
self.clocks[id].setSingleShot(True)
# and links it to the event() slot
self.clocks[id].timeout.connect(self.event(id))
# Finally calls the event() to start the timer
self.event(id)
# Sets the main window's geometry,
self.setGeometry(100, 100, 800, 400)
# and pushes it upfront
self.activateWindow()
@QtCore.pyqtSlot()
def event(self, id):
# Generates a random interval (or timeout) between 1ms and 10s
timeoutConstant = random.randint(1, 10000)
# Sets the new interval
self.clocks[id].setInterval(timeoutConstant)
# Refreshes the text in the associated label
self.indicators[id].setText("Time " + str(id) +" : " + str(timeoutConstant))
# Starts the freshly updated timer
self.clocks[id].start()
# Also prints a message to be able to track things
print("Timer " + str(id) + " over")
# Creates the app and start the QT process
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
However, the output is that :
argument 1 has unexpected type 'NoneType'
for the connect()
line ? I cannot wrap my head around why...
And list indices must be integers or slices, not QChildEvent
for the setInterval()
line ???
But how else could I manage a high number of these elements easily ? Thanks in advance for your help !
PS : Note that my code, when singularized, do run smoothly (tested with 1 and 2 timers and labels at the same time)...