Scripted Module Leak - Addobserver

Hi all.
My scripted module is giving me vtkDebugLeaks on termination of the Slicer Program.
It happens when I add an observer.

slicer.mrmlScene.AddObserver(“ModifiedEvent”, self.sliceModifiedCallback)

Is there a way to remove the observer upon program close?
Thanks!

Hello Dan,

You can remove an observer by using its tag. You get the tag when you add the observer [1].
For example:
self.observerTag = slicer.mrmlScene.AddObserver(vtk.vtkCommand.ModifiedEvent, self.sliceModifiedCallback)

You can then remove the observation by doing:
slicer.mrmlScene.RemoveObserver(self.example).

If you have a lot of events to observe, I would suggest that you take a look at the VTKObservationMixin. This should make it easier for you.

Thanks !
Johan
[1]: https://www.slicer.org/wiki/Documentation/Nightly/Developers/Python_scripting#How_can_I_access_callData_argument_in_a_VTK_object_observer_callback_function
[2]: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/util.py#L690

Thanks for the reply Johan.
I’ve actually seen that reference and was trying to figure out how to apply this to the module.

Is there a special method that will be called upon program close?
Where should I place
slicer.mrmlScene.RemoveObserver(self.observerTag )

Thanks.

DanC,

You could listen to the Qt signal sent by the qSlicerModuleFactoryManager::moduleAboutToBeUnloaded(QString). This signal should be sent when the application closes.
You can access the qSlicerModuleFactoryManager using the slicer application like so:
slicer.app.moduleManager().factoryManager().

Johan

Thanks.
That solved the problem.

moduleManager = slicer.app.moduleManager()
moduleManager.connect( 'moduleAboutToBeUnloaded(QString)', self.removeObserver )

def removeObserver(self):
self.redRenderer.RemoveObserver(self.observerTag )

Most often you remove observers in the cleanup() method of the module widget class. If you want to have observers only while the module is active then add observers in enter() and remove observers in exit() method of the widget class.

You can also use VTKObservationMixin, which makes adding observation simpler and automatically removes all observers when the owner class is deleted. See for example Segment editor module and VTKObservationMixin tests.