简体   繁体   中英

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM