实现这一点的最简单方法是使用生成器和“空闲计时器”。
这个想法是使用yield
关键字将您的循环变成一个生成器,这样您就可以使用next()
. 然后,您使用 Qt 的低级计时器(startTimer()
、killTimer()
和timerEvent()
)创建一个间隔为零的计时器,每次没有更多事件要处理时调用该计时器,以运行下一个循环迭代。这使您有机会在循环期间对 GUI 事件做出反应,例如,处理停止按钮clicked()
信号。
class MyWidget(QWidget): # Or whatever kind of widget you are creating
def __init__(self, parent, **kwargs):
super(MyWidget, self).__init__(parent, **kwargs)
# ... Create your widgets, connect signals and slots, etc.
self._generator = None
self._timerId = None
def loopGenerator(self):
# Put the code of your loop here
for a in range(3000):
self.ui.STATUS.setText("a=" + a)
# No processEvents() needed, just "pause" the loop using yield
yield
def start(self): # Connect to Start-button clicked()
self.stop() # Stop any existing timer
self._generator = self.loopGenerator() # Start the loop
self._timerId = self.startTimer(0) # This is the idle timer
def stop(self): # Connect to Stop-button clicked()
if self._timerId is not None:
self.killTimer(self._timerId)
self._generator = None
self._timerId = None
def timerEvent(self, event):
# This is called every time the GUI is idle.
if self._generator is None:
return
try:
next(self._generator) # Run the next iteration
except StopIteration:
self.stop() # Iteration has finshed, kill the timer