Search code examples
pythonqtpython-3.xpyqtsleep

Sleep is not working on pyqt4


I have got this problem. I´m trying to set text on a lineEdit object on pyqt4, then wait for a few seconds and changing the text of the same lineEdit. For this I´m using the time.sleep() function given on the python Time module. But my problem is that instead of setting the text, then waiting and finally rewrite the text on the lineEdit, it just waits the time it´s supposed to sleep and only shows the final text. My code is as follows:

from PyQt4 import QtGui
from gui import *

class Ventana(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)
        self.button.clicked.connect(self.testSleep)

    def testSleep(self):
        import time   
        self.lineEdit.setText('Start')
        time.sleep(2)
        self.lineEdit.setText('Stop')        

    def mainLoop(self, app ):
        sys.exit( app.exec_())

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Ventana()
    window.show()
    sys.exit(app.exec_())

Solution

  • You can't use time.sleep here because that freezes the GUI thread, so the GUI will be completely frozen during this time.

    You should probably use a QTimer and use it's timeout signal to schedule a signal for deferred delivery, or it's singleShot method.

    For example (adapted your code to make it run without dependencies):

    from PyQt4 import QtGui, QtCore
    
    class Ventana(QtGui.QWidget):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.setLayout(QtGui.QVBoxLayout())
            self.lineEdit = QtGui.QLineEdit(self)
            self.button = QtGui.QPushButton('clickme', self)
            self.layout().addWidget(self.lineEdit)
            self.layout().addWidget(self.button)
            self.button.clicked.connect(self.testSleep)
    
        def testSleep(self):
            self.lineEdit.setText('Start')
            QtCore.QTimer.singleShot(2000, lambda: self.lineEdit.setText('End'))
    
        def mainLoop(self, app ):
            sys.exit( app.exec_())
    
    if __name__ == '__main__':
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Ventana()
        window.show()
        sys.exit(app.exec_())