PyQt5 – QTime not changing values

Question:

I wanted to create a simple timer that gets shown to the screen and was using QTime to track the amount of time passed. However when I create a time with QTime(0, 0, 0) it will always stay at the initial value and will never change.

from PyQt5.QtCore import QTime

time = QTime(0, 0, 0)
print(time.toString("hh:mm:ss"))      # 00:00:00
    
time.addSecs(20)
print(time.toString("hh:mm:ss"))      # Still 00:00:00 for some reason

Why is the above code not updating the time variable and is there a simple fix for this?

Asked By: Ceadeus

||

Answers:

From the documentation the function signature is…

QTime QTime::addSecs(int s) const

So you need…

time = time.addSecs(20)
print(time.toString("hh:mm:ss"))
Answered By: G.M.

There is a super simple fix to this. time.addSecs(20) returns a value. So do time = time.addSecs(20) instead. That will fix your problem.

Answered By: CaptianFluffy100

The function name might be a bit counter intuitive, but the documentation is very clear about this.

It doesn’t say that addSecs() "Adds s seconds to this object", but that it

Returns a QTime object containing a time s seconds later than the time of this object"

(emphases mine)

Your time object does not change using addSecs().

The only way to change a QTime instance is by using setHMS().

If you want a convenience function that actually changes the time value for the same reference, you can do it by creating a new "patched" method at the very beginning of your code, right after the first PyQt import:

def adjustSecs(time, s):
   new = time.addSecs(s)
   time.setHMS(new.hour(), new.minute(), new.second(), new.msec())

QTime.adjustSecs = adjustSecs

# ...

t = QTime.currentTime()

print(t) # shows current time

t.adjustedSecs(3600)

print(t) # shows previous current time plus an hour
Answered By: musicamante
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.