睡眠在 pyqt4 上不起作用 [英] Sleep is not working on pyqt4

查看:53
本文介绍了睡眠在 pyqt4 上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题.我正在尝试在 pyqt4 上的 lineEdit 对象上设置文本,然后等待几秒钟并更改同一 lineEdit 的文本.为此,我使用了 Python Time 模块上给出的 time.sleep() 函数.但我的问题是,它不是设置文本,然后等待并最终重写 lineEdit 上的文本,而是等待它应该睡觉的时间,并且只显示最终文本.我的代码如下:

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

推荐答案

这里不能使用 time.sleep 因为它会冻结 GUI 线程,所以在这段时间内 GUI 会完全冻结.

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

您可能应该使用 QTimer 和使用它的 timeout 信号来安排延迟交付的信号,或者它的 singleShot 方法.

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

这篇关于睡眠在 pyqt4 上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆