Waiting for a timer to terminate before continuing running the code

大城市里の小女人 提交于 2019-12-25 03:16:31

问题


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.


回答1:


The solution I found that works was to replace

while True:
    if not self.timer.isActive():
        break

with

while self.timer.isActive():
    QtGui.QApplication.processEvents()

I'm not certain that this is the best solution, though.



来源:https://stackoverflow.com/questions/23867681/waiting-for-a-timer-to-terminate-before-continuing-running-the-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!