The following code updates the text of a button every second after the START
button was pressed. The intended functionality is for the code to 'wait' until the timer has stopped before continuing on with the execution of the code. That is, after START
is pressed, the text of the second button is incremented to 3
, and only then should the text I waited!
appear on the console.
import sys
from PySide import QtGui, QtCoreclass Example(QtGui.QWidget):def __init__(self, parent=None):super(Example, self).__init__(parent)self.app_layout = QtGui.QVBoxLayout()self.setLayout(self.app_layout)self.setGeometry(300, 300, 50, 50)self.current_count = 0self.count_to = 4self.delay = 1000self.timer = QtCore.QTimer(self)self.timer.timeout.connect(self.updateButtonCount) # start buttonstart_button = QtGui.QPushButton()start_button.setText('START')start_button.clicked.connect(self.startCount)self.app_layout.addWidget(start_button)# number buttonself.number_button = QtGui.QPushButton()self.number_button.setText('0')self.app_layout.addWidget(self.number_button)def updateButtonCount(self):self.number_button.setText("%s" % self.current_count)self.current_count += 1if self.current_count == self.count_to:self.timer.stop()def startCount(self):self.current_count = 0self.timer.start(self.delay)# this loop hangs the GUI:while True:if not self.timer.isActive():breakprint 'I waited!'def main():app = QtGui.QApplication(sys.argv)example = Example()example.show()sys.exit(app.exec_())if __name__ == '__main__':main()
The above code hangs the GUI, and if I remove the while True:
loop, the I waited!
appears immidiately on the console.
I'm certain that the while True:
loop is not the correct way to go about it, so I'm looking for suggestions.