Quantcast
Channel: mel wiki
Viewing all articles
Browse latest Browse all 610

How can I execute code when a window is deleted?

$
0
0
Often times I want to call a function when I close/delete a window. Unfortunately there is no 'delete detection' for this via the window command and no way via the window command to assign callbacks. However I've found two ways to implement callback systems that do detect for window deletion:
  • Via the OpenMayaUI API, one can create a MUiMessage_addUiDeletedCallback object that will track when the given window is deleted, and execute the provided code when that happens. It also allows for an optional clientData parameter allowing you to easily pass data to the function upon window delete.
    • Note: It appears that this code runs just before, or possibly at the same time as the window is deleted: It can be used to execute code to safely delete modelPanels before the window is deleted, when that same code would fail in the scriptJob callback.
  • It's easy to make a scriptJob which attaches itself to the window, executes when the window is deleted, and for safety can be set to only 'run once'. We have the scriptJob call to the a method on our Window object at time of death telling it what to do. It should be noted that this will execute the code after the window is closed.
It should be noted that the scriptJob needs to be called before showWindow or it won't seem to attach correctly.

Finally, even though these callbacks are executed when the window is closed, they appear to execute after the window is deleted. If you try to query part of the window ui in the callback, it will fail. I've got around this by storing the values I need to query in optionVar's.
# Python code
import maya.cmds as mc
import maya.OpenMayaUI as omui

class App(object):
    def __init__(self):
        self.name = 'myWin'
        if mc.window(self.name, exists=True):
            mc.deleteUI(self.name)
        mc.window(self.name)

        # OpenMayaUI callback example:
        omui.MUiMessage_addUiDeletedCallback(self.name, self.MUiMessageCallback, "clientData")

        # scriptJob callback example:
        mc.scriptJob(uiDeleted=[self.name, self.scriptJobCallback], runOnce=True)

        mc.showWindow()

    def MUiMessageCallback(self, clientData):
        print "MUiMessage_addUiDeletedCallback", clientData

    def scriptJobCallback(self, *args):
        print "scriptJobCallback", args
To launch the window:
App()
When the window is closed, it will print:
MUiMessage_addUiDeletedCallback clientData
scriptJobCallback ()
Notice how the MUiMessage_addUiDeletedCallback is executed first?

Viewing all articles
Browse latest Browse all 610

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>