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, QtCore
class 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 = 0
self.count_to = 4
self.delay = 1000
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.updateButtonCount)
# start button
start_button = QtGui.QPushButton()
start_button.setText('START')
start_button.clicked.connect(self.startCount)
self.app_layout.addWidget(start_button)
# number button
self.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 += 1
if self.current_count == self.count_to:
self.timer.stop()
def startCount(self):
self.current_count = 0
self.timer.start(self.delay)
# this loop hangs the GUI:
while True:
if not self.timer.isActive():
break
print '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.