About the time.sleep

for _ in range(20):
	n += 1
	print('n')
	time.sleep(1)

The printing results seems to be printed in the last time… Can I replace the time.sleep in slicer for waiting time?

Hi @timeanddoctor -

The native python time package is not integrated with the Slicer application event loop, managed by Qt. So you need to use QTimer methods instead.

Something like this:

for i in range(5):
   qt.QTimer.singleShot(1000*i, lambda i=i: print(i))

The other advantage is that the application will remain responsive while waiting for the time to elapse. Of course working asynchronously with the event loop is different from conventional sequential programming models, but it’s central to how the application works.

1 Like

If you must stay in a processing loop and still want to update the GUI then you can call slicer.app.processEvents():

for n in range(20):
    print(n)
    time.sleep(1)
    slicer.app.processEvents()  # update GUI