Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a timer in pyqt

I have a question that may be simple but i hav failed to get it solved I want to create a timer in pyqt using QTimeEdit with default time starting at 00:00:00 and increasing every second. I've tried the following code but it stops after adding only one second.

self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.time)
self.timer.start(1000)

def time(self):
    self.upTime.setTime(QtCore.QTime(00,00,00).addSecs())
like image 952
And3r50n 1 Avatar asked Dec 18 '22 10:12

And3r50n 1


2 Answers

{yout time}.addSecs(1) does not change time, but returns the changed time. Your must be use {yout time} = {yout time}.addSecs(1)

import sys

from PyQt5 import QtCore


def timerEvent():
    global time
    time = time.addSecs(1)
    print(time.toString("hh:mm:ss"))


app = QtCore.QCoreApplication(sys.argv)

timer = QtCore.QTimer()
time = QtCore.QTime(0, 0, 0)

timer.timeout.connect(timerEvent)
timer.start(1000)

sys.exit(app.exec_())

Output:

00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
00:00:06
00:00:07
00:00:08
00:00:09
00:00:10
00:00:11
00:00:12
#
like image 196
eyllanesc Avatar answered Dec 31 '22 14:12

eyllanesc


I can't test it but I think you need

self.curr_time = QtCore.QTime(00,00,00)

self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.time)
self.timer.start(1000)

def time(self):
    self.curr_time = self.curr_time.addSecs()
    self.upTime.setTime(self.curr_time))

You have to create QtCore.QTime(00,00,00) only once and later increase its value in time().

Now you always use QtCore.QTime(00,00,00) and increase this value.

like image 39
furas Avatar answered Dec 31 '22 12:12

furas