Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

Also, take a look at the QThread sleep() function, it puts the current thread to sleep and allows other threads to run. https://doc.qt.io/qt-5/qthread.html#sleep


Solution 3:

You can't use time.sleep here because that freezes the GUI thread, so the GUI will be completely frozen during this time.You can use QtTest module rather than time.sleep().

from PyQt4 import QtTest

QtTest.QTest.qWait(msecs)

So your code should look like:

from PyQt4 import QtGui,QtTest
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')
        QtTest.QTest.qWait(2000)
        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_())

Post a Comment for "Sleep Is Not Working On Pyqt4"