Equivalent to time.sleep for a PyQt application

Actually i was looking for time.sleep alternative to use in pyqt without using any thread concepts.

And the solution i figured out is:

from PyQt4 import QtTest

QtTest.QTest.qWait(msecs)

This works similar to time.sleep making GUI responsive.

Thankyou for your answers.


Maybe it could be done better but you can always use singleShot to run function with delay, and lambda to run function with argument.

import sys
from PyQt4 import QtGui, QtCore

#def num(self, i):
def num(i):
    print i
    i += 1
    if i < 999:
        # run again after 2000ms with argument
        QtCore.QTimer.singleShot(2000, lambda:num(i))
        #QtCore.QTimer.singleShot(2000, lambda:self.num(i))

app = QtGui.QApplication(sys.argv)

# run first time with start argument
num(1)
#QtCore.QTimer.singleShot(2000, lambda:num(1))

sys.exit(app.exec_())

I believe you are asking how to keep the GUI responsive if num() takes several seconds to run? You have two options:

  • if num() consists of many small chunks of "work", you can call application.processEvents() between the chunks, this will allow the GUI to respond to events. An easy situation to deal with is when most of the num() time is spent in a loop, then at the start or end of each iteration, call application.processEvents(). In your real application, if you don't have access to application, import qApp from PyQt4.
  • the better approach is to execute num() in a separate thread. There are many examples of this on SO (like this one). One way of doing that is

    • instantiate a QThread,
    • define a class (say NumberCruncher) that derives from QObject and defines num(self) and defines a signal 'done' emitted by num() before returning
    • call numberCruncher.moveToThread(thread)
    • connect the thread started signal to num
    • start the thread

Another option would be to process Qt events while waiting:

def num():
    for i in range(1, 999):
        print(i)
        # Sleep five seconds in total
        for _ in range(5 * 10):
            # Process events between short sleep periods
            QtWidgets.QApplication.processEvents()
            time.sleep(0.1)