lwangreen lwangreen - 23 days ago 11
Python Question

PyQt4 QTimer doesn't work

I'm new to use PyQt4 QTimer. I just copy the code from somewhere but seems it doesn't work. Can someone help me with this?

from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *



def startCount():
timer.start(1000)



def showNum():
global count
count = count + 1
return count

timer = QtCore.QTimer()
count = 0
timer.timeout.connect(showNum)
startCount()


I expect to see the count incremented by the time, but the console shows nothing as the output. Can someone explain this?

Answer

A QTimer cannot work without a running event-loop. Try this instead:

import sys
from PyQt4 import QtCore, QtGui

def startCount():
    timer.start(1000)

def showNum():
    global count
    count = count + 1
    print(count)
    if count > 10:
        app.quit()

app = QtCore.QCoreApplication(sys.argv)

timer = QtCore.QTimer()
count = 0
timer.timeout.connect(showNum)
startCount()

app.exec_()
Comments