Python maya.cmds.setParent() Examples

The following are 30 code examples of maya.cmds.setParent(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.cmds , or try the search function .
Example #1
Source File: ml_breakdown.py    From ml_tools with MIT License 7 votes vote down vote up
def quickBreakDownUI():
    winName = 'ml_quickBreakdownWin'
    if mc.window(winName, exists=True):
        mc.deleteUI(winName)

    mc.window(winName, title='ml :: QBD', iconName='Quick Breakdown', width=100, height=500)

    mc.columnLayout(adj=True)

    mc.paneLayout(configuration='vertical2', separatorThickness=1)
    mc.text('<<')
    mc.text('>>')
    mc.setParent('..')

    for v in (10,20,50,80,90,100,110,120,150):
        mc.paneLayout(configuration='vertical2',separatorThickness=1)

        mc.button(label=str(v)+' %', command=partial(weightPrevious,v/100.0))
        mc.button(label=str(v)+' %', command=partial(weightNext,v/100.0))
        mc.setParent('..')

    mc.showWindow(winName)

    mc.window(winName, edit=True, width=100, height=250) 
Example #2
Source File: interop.py    From P4VFX with MIT License 6 votes vote down vote up
def initializeMenu(self, entries):
        try:
            # gMainWindow = MayaInterop.main_parent_window()
            gMainWindow = maya.mel.eval('$temp1=$gMainWindow')
        except RuntimeError as e:
            print e
            print 'Are you running in Batch Python?'
            gMainWindow = None

        try:
            print 'Initialising menu...'
            self.perforceMenu = cmds.menu("PerforceMenu", parent=gMainWindow, tearOff=True, label='Perforce')
            cmds.setParent(self.perforceMenu, menu=True)
        except RuntimeError as e:
            print 'Maya error while trying to create menu:',
            print e 
Example #3
Source File: interop.py    From P4VFX with MIT License 6 votes vote down vote up
def initializeMenu(self, entries):
        try:
            # gMainWindow = MayaInterop.main_parent_window()
            gMainWindow = maya.mel.eval('$temp1=$gMainWindow')
        except RuntimeError as e:
            print e
            print 'Are you running in Batch Python?'
            gMainWindow = None

        try:
            print 'Initialising menu...'
            self.perforceMenu = cmds.menu("PerforceMenu", parent=gMainWindow, tearOff=True, label='Perforce')
            cmds.setParent(self.perforceMenu, menu=True)
        except RuntimeError as e:
            print 'Maya error while trying to create menu:',
            print e 
Example #4
Source File: ml_centerOfMass.py    From ml_tools with MIT License 6 votes vote down vote up
def buildMainLayout(self):
        '''Build the main part of the ui
        '''
        #self.cbBakeOnes = mc.checkBoxGrp(label='Bake on Ones',
                                         #annotation='Bake every frame. If deselected, the tool will preserve keytimes.')

        #mc.separator()
        self.ButtonWithPopup(label='Create Live COM',
                             command=createCenterOfMass,
                             annotation='Create a constrained COM node based on selected Root Control.')

        mc.paneLayout(configuration='vertical2',separatorThickness=1)
        self.ButtonWithPopup(label='Transfer Root Anim to COM',
                             command=bakeCenterOfMass,
                             annotation='Bake out the Root animation to the COM node.')
        self.ButtonWithPopup(label='Transfer COM back to Root',
                             command=bakeRoot,
                             annotation='A previously baked COM will be baked back to its corresponding Root.')
        mc.setParent('..') 
Example #5
Source File: ml_puppet.py    From ml_tools with MIT License 6 votes vote down vote up
def attributeMenuItem(node, attr):

    plug = node+'.'+attr
    niceName = mc.attributeName(plug, nice=True)

    #get attribute type
    attrType = mc.getAttr(plug, type=True)

    if attrType == 'enum':
        listEnum = mc.attributeQuery(attr, node=node, listEnum=True)[0]
        if not ':' in listEnum:
            return
        listEnum = listEnum.split(':')
        mc.menuItem(label=niceName, subMenu=True)
        for value, label in enumerate(listEnum):
            mc.menuItem(label=label, command=partial(mc.setAttr, plug, value))
        mc.setParent('..', menu=True)
    elif attrType == 'bool':
        value = mc.getAttr(plug)
        label = 'Toggle '+ niceName
        mc.menuItem(label=label, command=partial(mc.setAttr, plug, not value)) 
Example #6
Source File: ml_colorControl.py    From ml_tools with MIT License 6 votes vote down vote up
def colorControlLayout(self, label=''):
        mc.rowLayout( numberOfColumns=4,
                      columnWidth4=(150, 200, 90, 80),
                      adjustableColumn=2,
                      columnAlign=(1, 'right'),
                      columnAttach=[(1, 'both', 0),
                                    (2, 'both', 0),
                                    (3, 'both', 0),
                                    (4, 'both', 0)] )
        mc.text(label=label)
        colorSlider = mc.colorSliderGrp( label='', adj=2, columnWidth=((1,1),(3,1)))
        mc.button(label='From Selected',
                  ann='Get the color of the selected object.',
                  command=partial(self.setFromSelected, colorSlider))
        mc.button(label='Randomize',
                  ann='Set a random color.',
                  command=partial(self.randomizeColors, colorSlider))
        controls = mc.layout(colorSlider, query=True, childArray=True)

        mc.setParent('..')

        return colorSlider 
Example #7
Source File: optionbox.py    From cmt with MIT License 6 votes vote down vote up
def __init__(self, title, help_url=None):
        layout = mel.eval("getOptionBox")
        cmds.setParent(layout)
        mel.eval('setOptionBoxTitle("{}");'.format(title))
        self.create_ui()

        apply_close_button = mel.eval("getOptionBoxApplyAndCloseBtn;")
        cmds.button(apply_close_button, e=True, command=self._apply_and_close)
        apply_button = mel.eval("getOptionBoxApplyBtn;")
        cmds.button(apply_button, e=True, command=self._on_apply)
        close_button = mel.eval("getOptionBoxCloseBtn;")
        cmds.button(close_button, e=True, command=self._close)

        if help_url:
            help_item = mel.eval("getOptionBoxHelpItem;")
            cmds.menuItem(
                help_item,
                e=True,
                label="Help on {}".format(title),
                command='import webbrowser; webbrowser.open("{}")'.format(help_url),
            ) 
Example #8
Source File: ml_colorControl.py    From ml_tools with MIT License 5 votes vote down vote up
def buildMainLayout(self):
        '''Build the main part of the ui
        '''

        #tabs = mc.tabLayout()

        #tab1 = mc.columnLayout(adj=True)
        #self.swatch_selected = self.colorControlLayout()
        #mc.button(label='Color Selected', command=self.colorSelected)
        #mc.setParent('..')

        #tab2 = mc.columnLayout(adj=True)
        self.swatch_range1 = self.colorControlLayout(label='First Selected')
        self.swatch_range2 = self.colorControlLayout(label='Last Selected')
        mc.separator(horizontal=True, height=10)
        mc.button(label='Color Selected Nodes', command=self.colorSelectedRange)
        #mc.setParent('..')

        #tab3 = mc.columnLayout(adj=True)
        #self.positionWidgets = {}
        #for xyz in 'XYZ':
            #for m in ['Min','Max']:
                #self.positionWidgets[m+xyz] = self.colorControlLayout(label='{} {}'.format(m,xyz))

        mc.setParent('..')

        #mc.tabLayout( tabs, edit=True, tabLabel=((tab1, 'Color Control'), (tab2, 'Color Range')) ) 
Example #9
Source File: interop.py    From P4VFX with MIT License 5 votes vote down vote up
def addMenuSubmenu(self, label, icon, entries):
        try:
            cmds.menuItem(subMenu=True, tearOff=False, label=label, image=icon)
        except RuntimeError as e:
            print 'Maya error while trying to create submenu:',
            print e

        self.fillMenu(entries)

        try:
            cmds.setParent('..', menu=True )
        except RuntimeError as e:
            print 'Maya error while trying to change menu parent:',
            print e 
Example #10
Source File: reusableUI.py    From PythonForMayaSamples with GNU General Public License v3.0 5 votes vote down vote up
def buildUI(self):
        column = cmds.columnLayout()
        cmds.text(label="Use this slider to set the tween amount")

        cmds.rowLayout(numberOfColumns=2)
        self.slider = cmds.floatSlider(min=0, max=100, value=50, step=1, changeCommand=tweener.tween)
        cmds.button(label="Reset", command=self.reset)

        cmds.setParent(column)
        cmds.button(label="Close", command=self.close)

    # And again, we just need to override the reset method
    # We don't need to define the close, or show methods because it gets those from BaseWindow 
Example #11
Source File: reusableUI.py    From PythonForMayaSamples with GNU General Public License v3.0 5 votes vote down vote up
def buildUI(self):
        column = cmds.columnLayout()
        cmds.text(label="Use the slider to modify the number of teeth the gear will have")

        cmds.rowLayout(numberOfColumns=4)

        # This label will show the number of teeth we've set
        self.label = cmds.text(label="10")
        # Unlike the tweener, we use an integer slider and we set it to run the modifyGear method as it is dragged
        self.slider = cmds.intSlider(min=5, max=30, value=10, step=1, dragCommand=self.modifyGear)
        cmds.button(label="Make Gear", command=self.makeGear)
        cmds.button(label="Reset", command=self.reset)

        cmds.setParent(column)
        cmds.button(label="Close", command=self.close) 
Example #12
Source File: tweener.py    From PythonForMayaSamples with GNU General Public License v3.0 5 votes vote down vote up
def buildUI(self):
        # To start with we create a layout to hold our UI objects
        # A layout is a UI object that lays out its children, in this case in a column
        column = cmds.columnLayout()

        # Now we create a text label to tell a user how to use our UI
        cmds.text(label="Use this slider to set the tween amount")

        # We want to put our slider and a button side by side. This is not possible in a columnLayout, so we use a row
        row = cmds.rowLayout(numberOfColumns=2)

        # We create a slider, set its minimum, maximum and default value.
        # The changeCommand needs to be given a function to call, so we give it our tween function
        # We need to hold on to our slider's name so we can edit it later, so we hold it in a variable
        self.slider = cmds.floatSlider(min=0, max=100, value=50, step=1, changeCommand=tween)

        # Now we make a button to reset our UI, and it calls our reset method
        cmds.button(label="Reset", command=self.reset)

        # Finally we don't want to add anymore to our row layout but want to add it to our column again
        # So we must change the active parent layout
        cmds.setParent(column)

        # We add a button to close our UI
        cmds.button(label="Close", command=self.close)

    # *args will be a new concept for you
    # It basically means I do not know how many arguments I will get, so please put them all inside this one list (tuple) called args 
Example #13
Source File: ml_goToKeyframe.py    From ml_tools with MIT License 5 votes vote down vote up
def ui():
    '''
    user interface for ml_goToKeyframe
    '''

    with utl.MlUi('ml_goToKeyframe', 'Go To Keyframe', width=400, height=130, info='''Press Next and Previous to advance time to the next or previous keyframes
within the graph editor or your selection.
Check Round to Nearest Frame to avoid stopping time on non-whole frames.''') as win:

        mc.checkBoxGrp('ml_goToKeyframe_selected_checkBox',
                       label='Within Selection',
                       annotation='Only search for next and previous within the selected keys.',
                       changeCommand=uiSetCheckBox)
        mc.checkBoxGrp('ml_goToKeyframe_selectKeys_checkBox',
                       label='Select Keys',
                       annotation='Select the keyframe(s) on the frame navigated to.',
                       changeCommand=uiSetCheckBox)
        mc.checkBoxGrp('ml_goToKeyframe_round_checkBox',
                       label='Round to Nearest Frame',
                       annotation='Only go to whole-number frames, even if keys are on sub-frames.')
        mc.checkBoxGrp('ml_goToKeyframe_hierarchy_checkBox',
                       label='Search Hierarchy',
                       annotation='Go to the next or previous keyframe in the whole hierarchy.')

        mc.paneLayout(configuration='vertical2', separatorThickness=1)

        win.ButtonWithPopup(label='<< Previous', name=win.name, command=previous,
                            annotation='Go to previous keyframe.',
                            readUI_toArgs={'roundFrame':'ml_goToKeyframe_round_checkBox',
                                           'selected':'ml_goToKeyframe_selected_checkBox',
                                           'selectKeys':'ml_goToKeyframe_selectKeys_checkBox',
                                           'searchHierarchy':'ml_goToKeyframe_hierarchy_checkBox'})

        win.ButtonWithPopup(label='Next >>', name=win.name, command=next,
                            annotation='Go to next keyframe.',
                            readUI_toArgs={'roundFrame':'ml_goToKeyframe_round_checkBox',
                                           'selected':'ml_goToKeyframe_selected_checkBox',
                                           'selectKeys':'ml_goToKeyframe_selectKeys_checkBox',
                                           'searchHierarchy':'ml_goToKeyframe_hierarchy_checkBox'})
        mc.setParent('..') 
Example #14
Source File: AEsporeNodeTemplate.py    From spore with MIT License 5 votes vote down vote up
def add_brush_btn(self, attr):
        """ replace the default combobox with a button for each entry """

        cmds.rowLayout('instanceLayout', nc=8 ) #, adjustableColumn=6) #, w=270 ) #, columnWidth3=(80, 75, 150),  columnAlign=(1, 'right'), columnAttach=[(1, 'both', 0), (2, 'both', 0), (3, 'both', 0)] )
        cmds.text(l='Tool', align='right', w=145)
        cmds.button('placeBtn', l='Place', c=pm.Callback(self.activateContext, 'place', attr, 0))
        cmds.button('sprayBtn', l='Spray', c=pm.Callback(self.activateContext, 'spray', attr, 1))
        cmds.button('scaleBtn', l='Scale', c=pm.Callback(self.activateContext, 'scale', attr, 2))
        cmds.button('alignBtn', l='Align', c=pm.Callback(self.activateContext, 'align', attr, 3))
        cmds.button('moveBtn', l='Move', c=pm.Callback(self.activateContext, 'move', attr, 4))
        cmds.button('idBtn', l='Id', c=pm.Callback(self.activateContext, 'id', attr, 5))
        cmds.button('removeBtn', l='Remove', c=pm.Callback(self.activateContext, 'remove', attr, 6))
        cmds.setParent('..') 
Example #15
Source File: ml_controlLibrary.py    From ml_tools with MIT License 5 votes vote down vote up
def buildMainLayout(self):
        '''Build the main part of the ui
        '''

        tabs = mc.tabLayout()
        tab1 = mc.columnLayout(adj=True)

        mc.scrollLayout(cr=True)
        self.shelfLayout = mc.shelfLayout()

        self.refreshShelfLayout()

        mc.setParent(tabs)

        tab2 = mc.columnLayout(adj=True)

        mc.separator(height=8, style='none')
        mc.text('Select curve(s) to export. Multiple selected curves will be combined.')
        mc.text('Center and fit the curve in the viewport,')
        mc.text('and make sure nothing else is visible for best icon creation.')
        mc.separator(height=16, style='in')

        mc.button('Export Selected Curve', command=self.exportControl, annotation='Select a nurbsCurve to export.')

        mc.tabLayout( tabs, edit=True, tabLabel=((tab1, 'Import'),
                                                 (tab2, 'Export')
                                                 ))

        if not mc.shelfLayout(self.shelfLayout, query=True, numberOfChildren=True):
            mc.tabLayout( tabs, edit=True, selectTab=tab2) 
Example #16
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def buildWindow(self):
        '''
        Initialize the UI
        '''

        if mc.window(self.name, exists=True):
            mc.deleteUI(self.name)

        mc.window(self.name, title='ml :: '+self.title, iconName=self.title, width=self.width, height=self.height, menuBar=self.menu)


        if self.menu:
            self.createMenu()

        self.form = mc.formLayout()
        self.column = mc.columnLayout(adj=True)


        mc.rowLayout( numberOfColumns=2, columnWidth2=(34, self.width-34), adjustableColumn=2,
                      columnAlign2=('right','left'),
                      columnAttach=[(1, 'both', 0), (2, 'both', 8)] )

        #if we can find an icon, use that, otherwise do the text version
        if self.icon:
            mc.iconTextStaticLabel(style='iconOnly', image1=self.icon)
        else:
            mc.text(label=' _ _ |\n| | | |')

        if not self.menu:
            mc.popupMenu(button=1)
            mc.menuItem(label='Help', command=(_showHelpCommand(TOOL_URL+self.name+'/')))

        mc.text(label=self.info)
        mc.setParent('..')
        mc.separator(height=8, style='single', horizontal=True) 
Example #17
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def createMenu(self, *args):
        '''
        Create the main menu for the UI
        '''

        #generate shelf label by removing ml_
        shelfLabel = self.name.replace('ml_','')
        module = self.module
        if not module:
            module = self.name

        #if icon exists, use that
        argString = ''
        if not self.icon:
            argString = ', label="'+shelfLabel+'"'

        mc.menu(label='Tools')
        mc.menuItem(label='Add to shelf',
                    command='import ml_utilities;ml_utilities.createShelfButton("import '+module+';'+module+'.ui()", name="'+self.name+'", description="Open the UI for '+self.name+'."'+argString+')')
        if not self.icon:
            mc.menuItem(label='Get Icon',
                        command=(_showHelpCommand(ICON_URL+self.name+'.png')))
        mc.menuItem(label='Get More Tools!',
                    command=(_showHelpCommand(WEBSITE_URL+'/tools/')))
        mc.setParent( '..', menu=True )

        mc.menu(label='Help')
        mc.menuItem(label='About', command=self.about)
        mc.menuItem(label='Documentation', command=(_showHelpCommand(TOOL_URL+self.name+'/')))
        mc.menuItem(label='Python Command Documentation', command=(_showHelpCommand(TOOL_URL+'#\%5B\%5B'+self.name+'\%20Python\%20Documentation\%5D\%5D')))
        mc.menuItem(label='Submit a Bug or Request', command=(_showHelpCommand(WEBSITE_URL+'/about/')))

        mc.setParent( '..', menu=True ) 
Example #18
Source File: interop.py    From P4VFX with MIT License 5 votes vote down vote up
def addMenuSubmenu(self, label, icon, entries):
        try:
            cmds.menuItem(subMenu=True, tearOff=False, label=label, image=icon)
        except RuntimeError as e:
            print 'Maya error while trying to create submenu:',
            print e

        self.fillMenu(entries)

        try:
            cmds.setParent('..', menu=True )
        except RuntimeError as e:
            print 'Maya error while trying to change menu parent:',
            print e 
Example #19
Source File: mlSSDS.py    From ssds with MIT License 5 votes vote down vote up
def createUI():
    cmds.setParent('MayaWindow')
    try:
        cmds.menu('MukaiLab', query = True, label = True)
    except:
        cmds.menu('MukaiLab', label = 'MukaiLab')
    cmds.setParent('MukaiLab', menu = True)
    cmds.menuItem('SSDS', label = 'SSDS', command = showBuildWindow) 
Example #20
Source File: __init__.py    From mGui with MIT License 5 votes vote down vote up
def as_parent(self):
        try:
            cmds.setParent(self)
        except RuntimeError as e:
            cmds.setParent(self, menu=True)
        return self



# IMPORTANT NOTE
# this intentionally duplicates redundant property names from Control.
# That forces the metaclass to F-define the CtlProperties using cmds.layout
# instead of cmds.control. In Maya 2014, using cmds.control to query a layout fails,
# even for flags they have in common 
Example #21
Source File: __init__.py    From mGui with MIT License 5 votes vote down vote up
def __exit__(self, typ, value, tb):
        # by default, allow inner exceptions to propagate up
        # you can turn this off in production by
        # setting ignore_exceptions to true
        # if this is suppresed you should expect misleading
        # error messages if child controls error out; parent controls
        # may get fewer controls than they expect, but the real
        # problem is in the suppressed exception
        if typ and not self.ignore_exceptions:
            return False

        # look into the local namespace for Control-derived
        # objects with named vars. If they are children of the context manager
        # that is closing, add them with variable name as a key
        # this supports a more natural, keyless idiom (see 'add')

        owning_scope = inspect.currentframe().f_back
        if owning_scope.f_locals.get('mGui_expand_stack'):
            owning_scope = owning_scope.f_back
        for key, value in owning_scope.f_locals.items():
            if value in self:
                self.add(value, key)

        # restore the layout level
        Nested.ACTIVE_LAYOUT = self.__cache_layout
        self.__cache_layout = None
        self.layout()

        # restore gui parenting
        cmds.setParent(Nested.ACTIVE_LAYOUT) 
Example #22
Source File: ctx.py    From mGui with MIT License 5 votes vote down vote up
def create_property_ui(self, *_, **__):
        """
        override this in derived classes to create gui.

        You'll need to attach your gui to the results of set_ui_parent() and then
        close by activating the tab using set_active() as shown below
        """
        prop_sheet = self.set_ui_parent()
        cmds.columnLayout(self.name)
        cmds.text("no properties")
        cmds.setParent("..")
        self.set_active() 
Example #23
Source File: lists.py    From mGui with MIT License 5 votes vote down vote up
def redraw(self, *args, **kwargs):
        """
        NOTE: depends on the LIST_CLASS being set in the actual class!
        """
        try:
            cmds.waitCursor(st=1)

            self.clear()

            cmds.setParent(self)
            with self:
                with layouts.ScrollLayout('mgScroll#', childResizable=True) as inner_scroll:
                    with self.LIST_CLASS('mgList#', **self.redraw_options) as inner_list:
                        for item in self.collection:
                            w = self.template.widget(item)
                            self.widget_added(w)

            cmds.setParent(self)
            cmds.setParent("..")

            # controls only includes 'inner_scroll' for layout
            self.named_children['inner_scroll'] = inner_scroll
            self.named_children['inner_list'] = inner_list
            self.controls = [inner_scroll]


        finally:
            self.layout()
            cmds.waitCursor(st=0) 
Example #24
Source File: forms.py    From mGui with MIT License 5 votes vote down vote up
def fake_create(*args, **kwargs):
        return cmds.setParent(q=True) 
Example #25
Source File: _mixins.py    From mGui with MIT License 5 votes vote down vote up
def __init__(self, parent=None, *args, **kwargs):
        super(QWidgetBaseMixin, self).__init__(parent, *args, **kwargs)
        try:
            cmds.setParent(self)
        except RuntimeError:
            pass 
Example #26
Source File: QDialog.py    From mGui with MIT License 5 votes vote down vote up
def __init__(self, parent=None, *args, **kwargs):
        super(BaseDialog, self).__init__(parent, *args, **kwargs)
        template = 'dialogWindow{}'
        for i in count(1):
            name = template.format(i)
            if not cmds.window(name, exists=True):
                self.setObjectName(name)
                break
        cmds.setParent(self) 
Example #27
Source File: dagmenu.py    From mgear_core with MIT License 5 votes vote down vote up
def install():
    """ Installs dag menu option
    """

    # get state
    state = get_option_var_state()

    cmds.setParent(mgear.menu_id, menu=True)
    cmds.menuItem("mgear_dagmenu_menuitem", label="mGear Viewport Menu ",
                  command=run, checkBox=state)
    cmds.menuItem(divider=True)

    run(state) 
Example #28
Source File: shelf.py    From dpa-pipe with MIT License 5 votes vote down vote up
def exists(self):
        cmds.setParent(self.layout)
        return cmds.shelfLayout(self.name, q=True, exists=True)

    # ------------------------------------------------------------------------- 
Example #29
Source File: shelf.py    From dpa-pipe with MIT License 5 votes vote down vote up
def get(cls, name, layout=None):
        
        if not layout:
            layout = cls.top_level_layout()

        cmds.setParent(layout)
        shelf = cmds.shelfLayout(name, q=True, exists=True)

        if shelf:
            return cls(name, layout)
        else:
            raise NameError("Unable to find shelf: " + name)

    # ------------------------------------------------------------------------- 
Example #30
Source File: shelf.py    From dpa-pipe with MIT License 5 votes vote down vote up
def create(self):
        cmds.setParent(self.layout)
        cmds.shelfLayout(self.name)
        self._shelf_error_fix()

    # -------------------------------------------------------------------------