And3r50n 1
And3r50n 1

Reputation: 467

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())

Upvotes: 6

Views: 31929

Answers (4)

eyllanesc
eyllanesc

Reputation: 244282

{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
#

Upvotes: 8

Felipe
Felipe

Reputation: 1

Here is a solution:

import sys

from PySide import QtCore

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

app = QtCore.QCoreApplication(sys.argv)

timer0 = QtCore.QTimer()
time = QtCore.QTime(0, 0, 0)
timer0.setInterval(1000)
timer0.timeout.connect(calculo)
timer0.start()

sys.exit(app.exec_())

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120758

You just need to take the current time in the QTimeEdit and increase it by one second:

def time(self):
    self.upTime.setTime(self.upTime.time().addSecs(1))

And make sure the QTimeEdit is initialized properly whenever the up-time begins:

self.upTime.setTime(QtCore.QTime(0, 0, 0))
self.upTime.setDisplayFormat('hh:mm:ss')

Upvotes: 2

furas
furas

Reputation: 143057

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.

Upvotes: 2

Related Questions