Search code examples
pythonbuttonmaya

maya close window signal


I have created a ui from scratch using the commands within Maya documentation. The following function that I have wrote applies in two scenerios:

  1. When the user has clicked onto another button - Import, in which it will do as what it was written in the code then close it off with the following function (see readFile function)
  2. When user has clicked onto the button where it close the UI without running anything.

In my script, to cater the above two scenarios, I wrote as the following where closeWindow is catered to Scenario1 and cancelWindow is catered to Scenario2

def ui(self):
    ...
    cancelButton = cmds.button( label='Cancel', command=self.cancelWindow, width=150, height=35)

def closeWindow(self, *args):
    cmds.deleteUI(self.window, window=True)

def cancelWindow(self, *args):
    cmds.delete(camSel[0])
    cmds.deleteUI(self.window, window=True)

def readFile(self, *args):
    ...
    self.closeWindow()

As such, is it possible to create some sort of signal like those in PyQt (clicked(), returnPressed() etc) by combining the above 2 (automated + manual), seeing that the deleteUI command usage is the same?


Solution

  • Default Maya UI provides only callbacks, not signals. You can create a sort of 'pseudo signal' by calling an event handler object instead of a function. In that scenario the button only knows 'I fired the button event' and the handler can call as many functions as needed.

    class Handler(object):
    
        def __init__(self):
            self.handlers = []
    
        def add_handler (self, func):
            self.handlers.append(func)
    
        def __call__(self, *args, **kwargs):
            for eachfunc in handler:
                eachfunc(*args, **kwargs)
    
     hndl = Handler()
     hndl.add_handler(function1)  # do some ui work...
     hndl.add_handler(function2)  # do some scene work...
     hndl.add_handler(function3)  # do something over network, etc....
    
     b = cmds.button('twoFunctions', c = Hndl)
    

    In a large complex UI this is a nice way to keep minor things like button higlights and focus changes separated out from important stuff like changing the scene. In your application it's almost certainly overkill. You've only sharing 1 line between close and cancel, that's not too bad :)

    Heres' more background on on pseudo-events in maya gui.

    You can also use Maya's QT directly to get at the close event... Again, seems like overkill. More here