Sleep is not working on pyqt4

自作多情 提交于 2019-11-29 11:45:58

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

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_())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!