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?

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:

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 !

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 )



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:


That solved the problem.

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.