简体   繁体   中英

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM