Home > Mobile >  How to make button to perform multiple actions properly in PyQT5
How to make button to perform multiple actions properly in PyQT5

Time:08-05

Below is my test code. I'm trying to update the text of my label 2 times with a 10-sec delay in between when clicking the Button. However, it seems to always ignore the first action, in this case, which is self.display.setText("First") and run the second. I purposely put a 10-sec delay in between the actions to make sure the label not changing so fast that I can't see. I also tried swapping places of the first and second actions. Again, whichever is supposed to happen first is completely ignored. Please help!

import PyQt5.QtWidgets as qtwidget
import time

app = qtwidget.QApplication([])

class MainWindow(qtwidget.QWidget):
    def __init__(self):
        super().__init__()
        
        # Set window title
        self.setWindowTitle('Python')
        
        height = 100
        width = 500
        self.status = "stop"
        
        # Set fixed window size
        self.setFixedHeight(height)
        self.setFixedWidth(width)
        self.display = qtwidget.QLabel("Label")
        self.display.setStyleSheet("background-color: #e3e1da;\
                                    border: 1px solid black;\
                                    padding-left: 5px")
        
        self.btn1 = qtwidget.QPushButton("Button", self)
        self.btn1.clicked.connect(self.button_action)
        
        # Set progam main layout 
        main_layout = qtwidget.QVBoxLayout()
        
        # Create horizontal box for buttons
        sub_layout = qtwidget.QHBoxLayout()
        
        # Add buttons to horizontal box
        sub_layout.addWidget(self.btn1)
        
        # Add horizontal layout to vertical box layout
        main_layout.addLayout(sub_layout)
        main_layout.addWidget(self.display)
        
        
        self.setLayout(main_layout)
        self.show()

    def button_action(self):
        self.display.setText("First")
        time.sleep(5)
        self.display.setText("Second")
            
mw = MainWindow()

app.exec_()

CodePudding user response:

Taking feedback from the comments. I've modified my code and it's now working as intended.

    def button_action(self):
        self.display.setText("First")
        qtcore.QTimer.singleShot(100, lambda: self.test_function())
        
    def test_function(self):
        self.display.setText("Second")
  • Related