'Pyqt5 Start-Stop Button

I want to make a simple start/stop button. But I couldn't get the stop button to work. Can you help me with this?

def pressed(self):             
    self.infoLabel.clear()
    self.infoLabel.setText(self.infoLabel.text()+ " On The Way! Go chat.")
    self.goButton.setEnabled(False)
    self.stopPushButton.setEnabled(True)        
    while True:            
        randomTimer = float(random.uniform(6.2, 7.5))
        QtTest.QTest.qWait(randomTimer*1000)    
        myKeyboard.type("ABC")  
        myKeyboard.press(Key.enter)
        self.infoLabel.clear()
        self.infoLabel.setText(QtWidgets.QLabel(Dialog).text()+(" You typed ABC " + str(randomTimer)[0:5] + " seconds apart..."))            
        QtTest.QTest.qWait(3000)
        self.infoLabel.setText(QtWidgets.QLabel(Dialog).text()+(" Continue.. Wait the next type."))
        if self.stopPushButton.isEnabled(False):
            break            


def stopped(self):
    self.infoLabel.clear()
    self.infoLabel.setText(self.infoLabel.text()+ " Stopped!")        
    self.goButton.setEnabled(True)
    self.stopPushButton.setEnabled(False)


Solution 1:[1]

stopPushButton is an instance of QPushButton, it will never be equal to false, use the .enabled property to check if it is enabled.

Solution 2:[2]

Make the stop button togglable and check if self.stopPushButton.isChecked() in the loop, then reset its state in the stopped method for cleanliness.


    ...
    self.stopPushButton.setCheckable(True)
    ...


def pressed(self):             
    self.infoLabel.clear()
    self.infoLabel.setText(self.infoLabel.text()+ " On The Way! Go chat.")
    self.goButton.setEnabled(False)
    self.stopPushButton.setEnabled(True)
    while True:            
        randomTimer = float(random.uniform(16.2,19.5))
        QtTest.QTest.qWait(randomTimer*1000)    
        myKeyboard.type("ABC")  
        myKeyboard.press(Key.enter)
        self.infoLabel.clear()
        self.infoLabel.setText(QtWidgets.QLabel(Dialog).text()+(" You typed ABC " + str(randomTimer)[0:5] + " seconds apart..."))
        if self.stopPushButton.isChecked():
            break
        

def stopped(self):
    self.infoLabel.clear()
    self.infoLabel.setText(self.infoLabel.text()+ " Stopped!")        
    self.goButton.setEnabled(True)
    self.stopPushButton.setEnabled(False) 
    self.stopPushButton.setChecked(False)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ludwig
Solution 2 Guimoute