Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

python - 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_())
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...