Real Time Orientation Changing Through Python

Relatively new to 3D slicer. I have been looking at the reference guide that 3dslicer provided and found 3D object orientation can be changed through python. Currently this is the code I have where it prints a random yaw value and sends it to 3D slicer to change the orientation. The issue is that the orienation does not update but waits for the “while” loop to complete before updating the yaw orientation in 3D slicer. I would like to see the 3D object updated for each new yaw value if that is possible. Here is my code for reference. Any help would be appreciated.

import random
from time import sleep
count = 0
while True:
    yaw1 = random.randrange(90)
    layoutManager = slicer.app.layoutManager()
    threeDWidget = layoutManager.threeDWidget(0)
    threeDView = threeDWidget.threeDView()
    threeDView.yawDirection = threeDView.YawRight
    threeDView.setPitchRollYawIncrement(yaw1)
    threeDView.yaw()
    sleep(2)
    print(yaw1)
    count += 1
    if count >= 5:
        break

Maybe you are looking for something like this inside your for loop:

threeDView.setPitchRollYawIncrement(yaw1)
threeDView.yaw()
slicer.app.processEvents() # let's updates on the slicer scene happen

Hope it helps

1 Like

In addition to Mauro’s suggestion, I’d add that you shouldn’t use sleep in your Slicer python code. Instead you should use qt.QTimer related functions with callbacks so that your code integrates cleanly with the event loop like this example.