Search code examples
pythonqtpyqtpyqt4qtimer

How to design countdown with Qt


The code below creates a single QLabel and starts a countdown. Every second it prints a current time and how many seconds left.

enter image description here

Aside from printing the current time (Time now) I would like to print what time it is going to be when the count down reached the end. So the resulting message would look like this:

"Time now: 20:00:01. Countdown ends at: 20:00:16"

How to achieve it?

import datetime
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])

label = QtGui.QLabel()
label.resize(360, 40)
label.show()

count = 15
def countdown():
    global count 
    if count < 1:
        count = 15
    label.setText( 'Time now: %s. Seconds left: %s'%(datetime.datetime.now().strftime("%H:%M:%S"), count))
    count = count - 1

timer = QtCore.QTimer()
timer.timeout.connect(countdown)
timer.start(1000)

app.exec_()

Working solution:

(thanks to eyllanesc):

enter image description here

import datetime
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])

label = QtGui.QLabel()
label.resize(360, 40)
label.show()

count = 15
def countdown():
    global count 
    if count < 1:
        count = 15
    now = datetime.datetime.now()
    label.setText( 'Time now: %s. End time: %s. Seconds left: %s'%(now.strftime("%H:%M:%S"), (now + datetime.timedelta(seconds=count)).strftime("%H:%M:%S"), count))
    count = count - 1

interval = 1200
timer = QtCore.QTimer()
timer.timeout.connect(countdown)
timer.start(1000)

app.exec_()

Solution

  • You should have datetime.timedelta() added to the "remaining time":

     ...
     now = datetime.datetime.now()
     end = now + datetime.timedelta(seconds=count)
     label.setText('Time now: %s. Countdown ends at: %s' % (now.strftime("%H:%M:%S"), end.strftime("%H:%M:%S")))
     ...
    

    enter image description here