Search code examples
pythontimepyqtsleeppyside2

How to see more than one change in same function when using sleep in Python PySide2


I am trying to execute more than one action in same function. In the code below you are going to see a window page with a button and a label. I want to see "BLUE" and after 2 second of sleep I want to see "RED" text on my label. But when I click the button all function work like a block and after two second of slepp the label text changing to "RED". Yes first it change to BLUE but I can not see that because its too fast. How can I fix that?

class Form(QDialog):

def __init__(self, parent=None):
    super(Form, self).__init__(parent)
    #label is Hello now
    self.label=QLabel("Hello")
    self.button = QPushButton("Change it")
    layout = QVBoxLayout()
    layout.addWidget(self.label)
    layout.addWidget(self.button)
    self.setLayout(layout)
    self.button.clicked.connect(self.func)
def func(self):
    self.label.setText("BLUE")
    time.sleep(2)
    self.label.setText("RED")

Solution

  • void QTimer::singleShot(int msec, const QObject *receiver, const char *member)

    This static function calls a slot after a given time interval.

    from PyQt5.QtCore    import *
    from PyQt5.QtGui     import *
    from PyQt5.QtWidgets import *
    
    class Form(QDialog):
    
        def __init__(self, parent=None):
            super(Form, self).__init__(parent)
            
            #label is Hello now
            self.label  = QLabel("Hello")
            self.button = QPushButton("Change it")
            self.button.clicked.connect(self.func)
            
            layout = QVBoxLayout()
            layout.addWidget(self.label)
            layout.addWidget(self.button)
            self.setLayout(layout)
            
        def func(self):
            self.label.setText("BLUE")
    #        QApplication.processEvents()      
    #        QThread.msleep(2000)              
    #        self.label.setText("RED")
            QTimer.singleShot(2000, lambda : self.label.setText("RED"))       # <----
        
    if __name__ == "__main__":
        import sys
        app = QApplication(sys.argv)
        w = Form()
        w.show()
        sys.exit(app.exec_())
    

    enter image description here