Search code examples
pythonmaya

Update optionMenu items every time selection is changed in a textScrollList


I have a window that has both a textScrollList and an optionMenu. I would like to refresh the option menu items whenever a selection is changed in the text list.

Not really sure to start on this one.

I'm using regular Maya Python.


Solution

  • The basic trick is just to make sure your update function is defined in a way that lets it know the names of both the optionMenu and the textScrollList so it can edit them. The easy way is to define the callback after both items are declared and stored in variables - as long as this is all in one scope python will automatically insert the values you need via a closure - it's much more elegant than doing it manually

    Here's a very minimal example

    w = cmds.window()
    c = cmds.columnLayout()
    sl = cmds.textScrollList( append = ['a', 'b', 'c'])
    op = cmds.optionMenu(label = 'test')
    cmds.menuItem('created by default')
    
    
    # the callback is defined after the ui so it knows the values of 'sl' and 'op'
    
    def edit_options():
        # gets a list of selected items from the textScroll
        selected = cmds.textScrollList(sl,q=True, si=True)
    
        # loop through existing menus in the optionMenu and destroy them
        for item in cmds.optionMenu(op, q=True, ill=True) or []:
            cmds.deleteUI(item)
    
        # add a new entry for every item in the selection
        for item in selected:
            cmds.menuItem(label = item, parent = op)
    
        # and something not dependent on the selection too
        cmds.menuItem(label = 'something else', parent = op)
    
    # hook the function up - it will remember the control names for you
    cmds.textScrollList(sl, e=True, sc = edit_options)
    
    cmds.showWindow(w)
    

    More background: http://techartsurvival.blogspot.com/2014/04/maya-callbacks-cheat-sheet.html