def convert(mguiName): """ From the name of a Maya UI element of any type to pointer, and wrap the pointer into a python QObject :param mguiName: Maya UI Name :type mguiName: string :return: QWidget or subclass instance :rtype: QtGui.QWidget Thanks to Nathan Horne """ # Get pointer ptr = MQtUtil.findControl(mguiName) if ptr is None: ptr = MQtUtil.findLayout(mguiName) if ptr is None: ptr = MQtUtil.findMenuItem(mguiName) if ptr is None: return None # Find corresponding class qObj = wrapInstance(long(ptr), QtCore.QObject) metaObj = qObj.metaObject() cls = metaObj.className() superCls = metaObj.superClass().className() if hasattr(QtGui, cls): base = getattr(QtGui, cls) elif hasattr(QtGui, superCls): base = getattr(QtGui, superCls) else: base = QtGui.QWidget return wrapInstance(long(ptr), base)
def convert(mguiName): """ From the name of a Maya UI element of any type to pointer, and wrap the pointer into a python QObject :param mguiName: Maya UI Name :type mguiName: string :return: QWidget or subclass instance :rtype: QtWidgets.QWidget Thanks to Nathan Horne """ # Get pointer ptr = MQtUtil.findControl(mguiName) if ptr is None: ptr = MQtUtil.findLayout(mguiName) if ptr is None: ptr = MQtUtil.findMenuItem(mguiName) if ptr is None: return None # Find corresponding class qObj = QtCompat.wrapInstance(long(ptr), QtCore.QObject) metaObj = qObj.metaObject() cls = metaObj.className() superCls = metaObj.superClass().className() if hasattr(QtWidgets, cls): base = getattr(QtWidgets, cls) elif hasattr(QtWidgets, superCls): base = getattr(QtWidgets, superCls) else: base = QtWidgets.QWidget return QtCompat.wrapInstance(long(ptr), base)
def get_q_object(element_name): """ :param element_name: str(<maya_element_name>) :return: QObject """ pointer = MQtUtil.findControl(element_name) if not pointer: pointer = MQtUtil.findLayout(element_name) if not pointer: pointer = MQtUtil.findMenuItem(element_name) return shiboken.wrapInstance(pointer, QtCore.QObject)
def __init__(self, workspace_control_name=None): super(MyDockableButton, self).__init__() self.setWindowTitle("Dockable Window") self.setText("My Button") if workspace_control_name: workspace_control_ptr = long( MQtUtil.findControl(workspace_control_name)) widget_ptr = long(getCppPointer(self)[0]) MQtUtil.addWidgetToMayaLayout(widget_ptr, workspace_control_ptr)
def getChildWin(title, widgType=QtWidgets.QWidget): for w in getMayaMainWindow().children(): if w.isWidgetType() and w.windowTitle() == title: return w else: ptr = MQtUtil.findControl(title) if not ptr: ptr = MQtUtil.findWindow(title) if not ptr: ptr = MQtUtil.findLayout(title) if not ptr: return return shiboken2.wrapInstance(long(ptr), widgType)
def setupMannequinUI(): """Sets up the side panel UI for the Mannequin plugin.""" currentContext = cmds.currentCtx() influenceObjectsStr = cmds.mannequinContext(currentContext, q=True, io=True) ioTokens = influenceObjectsStr.split(" ") ioDagPaths = ioTokens[::2] ioAvailableStyles = ioTokens[1::2] mannequinDockPtr = MQtUtil.findLayout("mannequinPaletteDock") mannequinDock = wrapInstance(long(mannequinDockPtr), QWidget) mannequinDock.setMinimumWidth(300) mannequinLayoutPtr = MQtUtil.findLayout("mannequinPaletteLayout") mannequinLayout = wrapInstance(long(mannequinLayoutPtr), QWidget) mannequinSearchPtr = MQtUtil.findControl("mannequinSearchField") mannequinSearch = wrapInstance(long(mannequinSearchPtr), QLineEdit) uiFile = QFile(os.path.join(os.path.dirname(__file__), "mannequin.ui")) uiFile.open(QFile.ReadOnly) gui = mannequinToolPanel.loader.load(uiFile, parentWidget=mannequinLayout) uiFile.close() selList = om.MSelectionList() for obj in ioDagPaths: selList.add(obj) joints = [] for i in range(selList.length()): dagPath = selList.getDagPath(i) dependNode = selList.getDependNode(i) styles = ioAvailableStyles[i] joints.append(JointInfo(dagPath, dependNode, styles)) # Alphabetize joints by full DAG path; should sort slightly better. joints = sorted(joints, key=lambda j: j.dagPath.fullPathName()) prefixTrim = commonPrefix(joints) mannequinToolPanel.reset(mannequinLayout, gui, mannequinSearch, prefixTrim) jointDisplays = organizeJoints(joints) for jointDisplay in jointDisplays: mannequinToolPanel.layoutJointGroup(jointDisplay) mannequinToolPanel.finishLayout()
def MayaWindow(): """Fetch Maya window""" global maya_window # This will never change during the lifetime of this Python session if not maya_window: from maya.OpenMayaUI import MQtUtil ptr = MQtUtil.mainWindow() try: # Backwards compatibility with Python 2.x long except NameError: long = int if ptr is not None: maya_window = shiboken2.wrapInstance( long(ptr), QtWidgets.QMainWindow ) else: # Running standalone return None return maya_window
def __init__(self): super(MyDockableButtonStatic, self).__init__() self.setObjectName(self.UI_NAME) self.setWindowTitle("Dockable Window") self.setText('My Button') workspace_control_name = "{0}WorkspaceControl".format(self.UI_NAME) if cmds.workspaceControl(workspace_control_name, q=True, exists=True): workspace_control_ptr = long( MQtUtil.findControl(workspace_control_name)) widget_ptr = long(getCppPointer(self)[0]) MQtUtil.addWidgetToMayaLayout(widget_ptr, workspace_control_ptr)
def getMayaWindow(): ''' return maya window by Qt object.. ''' ptr = MQtUtil.mainWindow() if ptr is not None: return sip.wrapinstance(long(ptr),QtCore.QObject)
def getMayaWindow(): ''' return maya window by Qt object.. ''' ptr = MQtUtil.mainWindow() if ptr is not None: return sip.wrapinstance(long(ptr), QtCore.QObject)
def __init__(self): # Sanity check : Plugin if not Method.load_plugin(): QtGui.QMessageBox.information( None, "Sol", "Sol's {} plugin is not loaded.\n" "UI could not be started.".format(Vars.PLUGIN_NAME) ) return # Sanity check : Viewport Renderer if not Dialogs.ViewportWarning.check(): return # Single UI if pmc.windows.window(Vars.WINDOW_NAME, exists=True): pmc.windows.deleteUI(Vars.WINDOW_NAME) # QWidget init super(SolControlUI, self).__init__( shiboken.wrapInstance(long(MQtUtil.mainWindow()), QtGui.QWidget) ) self._init_vars() self._init_ui() self._init_toolbar() self.reload_ui()
def maya_main_window(): """Returns the open maya window. Return: wrapInstance: The maya window as a WrapInstance object. """ main_window = MQtUtil.mainWindow() return wrapInstance(long(main_window), QtWidgets.QWidget)
def window_close_all_pyside(cls): MAYA_WINDOW = wrapInstance(long(MQtUtil.mainWindow()), QtCore.QObject) # For QMainWindow if MAYA_WINDOW.findChildren(QtGui.QMainWindow): for children in MAYA_WINDOW.findChildren(QtGui.QMainWindow): children.close()
def getMayaMainWindow(): from maya.OpenMayaUI import MQtUtil import shiboken from PySide import QtGui # returns a QWidget wrapper for the main maya window, # to allow uiMaster to be parented to it mayaWin = MQtUtil.mainWindow() if mayaWin: return shiboken.wrapInstance(long(mayaWin), QtGui.QMainWindow)
def run(): maya_ui = MQtUtil.mainWindow() maya_ui_qt = shiboken.wrapInstance(long(maya_ui), QtWidgets.QMainWindow) closeExisting(maya_ui_qt) window = QRegexSimulator(maya_ui_qt) window.show()
def active_panel_widget(): from maya import cmds from maya.OpenMayaUI import MQtUtil try: from shiboken import wrapInstance except ImportError: from shiboken2 import wrapInstance panel = cmds.getPanel(withFocus=True) widget = wrapInstance(long(MQtUtil.findControl(panel)), QtWidgets.QWidget) return MayaWidget(panel, widget)
def get_maya_window(): """ Get Maya MainWindow as a QWidget. :raises: None :return: Maya's main window. :rtype: QtGui.QMainWindow """ ptr = long(MQtUtil.mainWindow()) return shiboken.wrapInstance(ptr, QtGui.QMainWindow)
def __init__(self, name='scriptEditor', path='', **kwargs): parentName = cmds.setParent(q=True) p = MQtUtil.findLayout(parentName) lytWd = wrapInstance(long(p), QtWidgets.QWidget) widget = ScriptEditorWidget(name, textChangeHandler=self.textChanged, **kwargs) lytWd.layout().addWidget(widget) self.__widget_ref = _weakref(widget) self.editor = parentName + '|' + name super(ScriptEditor, self).__init__(path or self.editor)
def maya_widget(widget): '''QWidget to MayaWidget''' from maya.OpenMayaUI import MQtUtil try: from shiboken import getCppPointer except ImportError: from shiboken2 import getCppPointer pointer = long(getCppPointer(widget)[0]) path = MQtUtil.fullName(pointer) return MayaWidget(path, widget)
def get_maya_main_window(): """ :return: OpenMayaUI.MQtUtil.mainWindow() -> QMainWindow """ pointer = MQtUtil.mainWindow() if pointer is None: raise RuntimeError('Maya main window not found.') window = wrap_instance(pointer, QtGui.QMainWindow) assert isinstance(window, QtGui.QMainWindow) return window
def wrap(): i = 1 while i: try: se_edit = wrapInstance(long(MQtUtil.findControl('cmdScrollFieldReporter%i' % i)), QTextEdit) break except TypeError: i += 1 try: syntax_highlighter.deleteLater() except: pass syntax_highlighter = SH(se_edit)
def get_shader(self, shader): """Wrap and return a maya material swatch as a QWidget""" port = cmds.swatchDisplayPort(sn=shader, widthHeight=[32, 32], width=32, height=32, renderSize=32, backgroundColor=[0, 0, 0]) ptr = MQtUtil.findControl(port) qport = shiboken2.wrapInstance(long(ptr), QtWidgets.QWidget) qport.setFixedSize(32, 32) return qport
def get_maya_main_window(): """ :return: QMainWindow """ # noinspection PyArgumentList pointer = MQtUtil.mainWindow() if not pointer: raise RuntimeError('get_maya_main_window(): QMainWindow not found.') window = wrap_instance(pointer, QtWidgets.QMainWindow) assert isinstance(window, QtWidgets.QMainWindow) return window
def build_workspace_control_ui(shotgun_panel_name): """ Embeds a Shotgun app panel into the calling Maya workspace control. This function will be called in two cases: - When the workspace control is being created by Maya command workspaceControl; - When the workspace control is being restored from a workspace control state created by Maya when this workspace control was previously closed and deleted. .. note:: This function is only for Maya 2017 and later. :param shotgun_panel_name: Name of the Qt widget at the root of a Shotgun app panel. """ import maya.api.OpenMaya import maya.utils from maya.OpenMayaUI import MQtUtil # In the context of this function, we know that we are running in Maya 2017 and later # with the newer versions of PySide and shiboken. from PySide2 import QtWidgets from shiboken2 import wrapInstance # Retrieve the calling Maya workspace control. ptr = MQtUtil.getCurrentParent() workspace_control = wrapInstance(long(ptr), QtWidgets.QWidget) # Search for the Shotgun app panel widget. for widget in QtWidgets.QApplication.allWidgets(): if widget.objectName() == shotgun_panel_name: # Reparent the Shotgun app panel widget under Maya workspace control. widget.setParent(workspace_control) # Add the Shotgun app panel widget to the Maya workspace control layout. workspace_control.layout().addWidget(widget) # Install an event filter on Maya workspace control to monitor # its close event in order to reparent the Shotgun app panel widget # under Maya main window for later use. panel_util.install_event_filter_by_widget(workspace_control, shotgun_panel_name) break else: msg = "Shotgun: Cannot restore %s: Shotgun app panel not found" % shotgun_panel_name fct = maya.api.OpenMaya.MGlobal.displayError maya.utils.executeInMainThreadWithResult(fct, msg)
def __init__(self, parent=None): super(self.__class__, self).__init__(parent=parent) mayaMainWindowPtr = MQtUtil.mainWindow() #self.mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QMainWindow) # Yaml File Load fileYamlLocation = "C:/Users/KrisPC/Desktop/Tool.yaml" ymlFile = open(fileYamlLocation, "r") #Load in the yml File self.ymlInfo = yaml.load(ymlFile, Loader=yaml.FullLoader) comboUsernameID = (self.ymlInfo["user"]["usernameID"]) comboFT = (self.ymlInfo["user"]["filetype"]) # Window Settings self.setWindowFlags(QtCore.Qt.Window) self.setWindowTitle('Import/Export Tool') self.resize(300, 100) # UI Options # Labels and Combo Boxes self.comboUserLabel = QLabel("Username:"******"File Type:") self.comboUserBox = QComboBox() self.comboUserBox.addItems(comboUsernameID) self.comboFTBox = QComboBox() self.comboFTBox.addItems(comboFT) # Buttons self.helpButton = QPushButton('Help') self.importButton = QPushButton('Import') self.exportButton = QPushButton('Export') self.helpButton.clicked.connect(self.buttonHelp) self.importButton.clicked.connect(self.buttonImport) self.exportButton.clicked.connect(self.buttonExport) # Main Layout self.mainLayout = QVBoxLayout() self.mainLayout.addWidget(self.comboUserLabel) self.mainLayout.addWidget(self.comboUserBox) self.mainLayout.addWidget(self.comboFTLabel) self.mainLayout.addWidget(self.comboFTBox) self.mainLayout.addWidget(self.importButton) self.mainLayout.addWidget(self.exportButton) self.mainLayout.addWidget(self.helpButton) self.setLayout(self.mainLayout)
def dpaf_makePySideUI(self, ctrlName, myStyle): # thanks to Nathan Horne ctrlName = long(MQtUtil.findControl(ctrlName)) qObj = wrapInstance(ctrlName, QtCore.QObject) metaObj = qObj.metaObject() cls = metaObj.className() superCls = metaObj.superClass().className() if hasattr(QtGui, cls): base = getattr(QtGui, cls) elif hasattr(QtGui, superCls): base = getattr(QtGui, superCls) else: base = QtGui.QWidget uiPySide = wrapInstance(ctrlName, base) uiPySide.setStyleSheet(myStyle)
def dp_makePySideUI(ctrlName, myStyle): # thanks to Nathan Horne ctrlName = long(MQtUtil.findControl(ctrlName)) qObj = wrapInstance(ctrlName, QtCore.QObject) metaObj = qObj.metaObject() cls = metaObj.className() superCls = metaObj.superClass().className() if hasattr(QtGui, cls): base = getattr(QtGui, cls) elif hasattr(QtGui, superCls): base = getattr(QtGui, superCls) else: base = QtGui.QWidget uiPySide = wrapInstance(ctrlName, base) uiPySide.setStyleSheet(myStyle)
def run(pos=None): maya_ui = MQtUtil.mainWindow() maya_ui_qt = shiboken.wrapInstance(long(maya_ui), QtWidgets.QMainWindow) closeExisting(maya_ui_qt) window = PaletteEditor(maya_ui_qt) window.show() # center window on mouse position if pos: window_size = window.size() centered_pos = ( pos.x() -window_size.width()/2, pos.y() -window_size.height()/2, ) window.move(*centered_pos)
def __init__(self): # Get maya pointer, kill existing reloader maya = wrapInstance(long(MQtUtil.mainWindow()), QtGui.QWidget) for c in maya.findChildren(QtGui.QWidget): if self.WINDOW_TITLE in c.windowTitle(): c.close() # Init link to maya QtGui.QWidget.__init__(self, maya) self.setWindowFlags(QtCore.Qt.Window) # Init vars and UI self._init_data() self._init_ui() self._reload_ui() # Show self.show()
def execute(): # Get the application this has been run from appname = get_application() # For the status of our window global muggins # Now continue running in either Maya or Default Mode if appname == 'maya': main_window_ptr = MQtUtil.mainWindow() parent = wrapinstance(long(main_window_ptr), QtCore.QObject) # If it exists delete it try: muggins.deleteLater() except: pass # If there's an error creating it...DELETE it! try: muggins = MugginsUI(parent=parent) except: muggins.deleteLater() print_exc()
def execute(): # Get the application this has been run from interpreterPath=sys.executable [filepath,filename]=os.path.split(interpreterPath) appname=filename.split('.')[0] # For the status of our window global ccUI # Now continue running in either Maya or Default Mode if appname.lower() == 'maya': main_window_ptr = MQtUtil.mainWindow() parent = wrapInstance(long(main_window_ptr), QtGui.QWidget) # If it exists delete it try: ccUI.deleteLater() except: pass # If there's an error creating it...DELETE it! try: ccUI = carCleanUI(parent=parent) except: #ccUI.deleteLater() print_exc()
def __init__(self, name='scriptEditor', parent=None, textChangeHandler=None, **kwargs): super(ScriptEditorWidget, self).__init__(parent) self.setObjectName(name) self.__layout = QtWidgets.QVBoxLayout(self) self.__layout.setContentsMargins(0,0,0,0) self.mayaEditor = cmds.cmdScrollFieldExecuter( st='python', searchWraps=True, filterKeyPress=self.__keyPress, cco=False, opc=False, sth=False, # acb=False, **kwargs) self.__txt = '' p = MQtUtil.findControl(self.mayaEditor) self.editor = p and wrapInstance(long(p), QtWidgets.QTextEdit) if self.editor: self.editor.setParent(self) if textChangeHandler: self.__textChangeHandler = textChangeHandler self.editor.installEventFilter(self) #self.editor.textChanged.connect(self.__textChanged) self.__layout.addWidget(self.editor)
def _find_widget_ptr(widget): ptr = (MQtUtil.findControl(widget) or MQtUtil.findLayout(widget) or MQtUtil.findMenuItem(widget)) return ptr
def getMayaMainWindow(): # returns a QWidget wrapper for the main maya window, # to allow uiMaster to be parented to it mayaWin = MQtUtil.mainWindow() if mayaWin: return shiboken2.wrapInstance(long(mayaWin), QtWidgets.QMainWindow)
def get_anchor(): ptr = MQtUtil.mainWindow() return wrapInstance(long(ptr), QMainWindow)
def build_workspace_control_ui(shotgun_panel_name): """ Embeds a Shotgun app panel into the calling Maya workspace control. This function will be called in two cases: - When the workspace control is being created by Maya command workspaceControl; - When the workspace control is being restored from a workspace control state created by Maya when this workspace control was previously closed and deleted. .. note:: This function is only for Maya 2017 and later. :param shotgun_panel_name: Name of the Qt widget at the root of a Shotgun app panel. """ from maya.OpenMayaUI import MQtUtil # In the context of this function, we know that we are running in Maya 2017 and later # with the newer versions of PySide and shiboken. from PySide2 import QtWidgets from shiboken2 import wrapInstance import sgtk.platform # Retrieve the Maya engine. engine = sgtk.platform.current_engine() # Retrieve the calling Maya workspace control. ptr = MQtUtil.getCurrentParent() workspace_control = wrapInstance(long(ptr), QtWidgets.QWidget) # Search for the Shotgun app panel widget. for widget in QtWidgets.QApplication.allWidgets(): if widget.objectName() == shotgun_panel_name: maya_panel_name = workspace_control.objectName() engine.logger.debug("Reparenting Shotgun app panel %s under Maya workspace panel %s.", shotgun_panel_name, maya_panel_name) # When possible, give a minimum width to the workspace control; # otherwise, it will use the width of the currently displayed tab. # Note that we did not use the workspace control "initialWidth" and "minimumWidth" # to set the minimum width to the initial width since these values are not # properly saved by Maya 2017 in its layout preference files. # This minimum width behaviour is consistent with Maya standard panels. size_hint = widget.sizeHint() if size_hint.isValid(): # Use the widget recommended width as the workspace control minimum width. minimum_width = size_hint.width() engine.logger.debug("Setting Maya workspace panel %s minimum width to %s.", maya_panel_name, minimum_width) workspace_control.setMinimumWidth(minimum_width) else: # The widget has no recommended size. engine.logger.debug("Cannot set Maya workspace panel %s minimum width.", maya_panel_name) # Reparent the Shotgun app panel widget under Maya workspace control. widget.setParent(workspace_control) # Add the Shotgun app panel widget to the Maya workspace control layout. workspace_control.layout().addWidget(widget) # Install an event filter on Maya workspace control to monitor # its close event in order to reparent the Shotgun app panel widget # under Maya main window for later use. engine.logger.debug("Installing a close event filter on Maya workspace panel %s.", maya_panel_name) panel_util.install_event_filter_by_widget(workspace_control, shotgun_panel_name) # Delete any leftover workspace control state to avoid a spurious deletion # of our workspace control when the user switches to another workspace and back. if cmds.workspaceControlState(maya_panel_name, exists=True): # Once Maya will have completed its UI update and be idle, # delete the leftover workspace control state. engine.logger.debug("Deleting leftover Maya workspace control state %s.", maya_panel_name) maya.utils.executeDeferred(cmds.workspaceControlState, maya_panel_name, remove=True) break else: # The Shotgun app panel widget was not found and needs to be recreated. # Search for the Shotgun app panel that needs to be restored # among the panels registered with the engine. for panel_id in engine.panels: # The name of the Qt widget at the root of the Shotgun app panel # was constructed by prepending to the panel unique identifier. if shotgun_panel_name.endswith(panel_id): # Once Maya will have completed its UI update and be idle, # recreate and dock the Shotgun app panel. maya.utils.executeDeferred(engine.panels[panel_id]["callback"]) break else: # The Shotgun app panel that needs to be restored is not in the context configuration. engine.logger.error("Cannot restore %s: Shotgun app panel not found. " \ "Make sure the app is in the context configuration. ", shotgun_panel_name)
def maya_main_window(): """ Return s the Maya main window as a Python Object """ main_window_ptr = MQtUtil.mainWindow() # Python API 1.0 return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)
def __init__(self): self.WIDTH = 0 self.HEIGHT = 0 self.timer = None self.mouse_start_position = (0, 0) # Set windows main_window = long(MQtUtil.mainWindow()) parent = wrapInstance(main_window, QtGui.QWidget) super(cameraOverShoot, self).__init__(parent) # Container Widget master_widget = QtGui.QWidget() self.setCentralWidget(master_widget) self.setWindowTitle("Camera overs shoot") # Master layout master_layout = UiElement.base_layout(parent=master_widget) # ComboBox labels = ['Camera', 'Panel'] items = [self.get_all_camera(), self.get_model_editor()] self.combobox_select = UiElement.comboBox( master_layout, labels, items, [(90, 0, 30), ] * 2, margin=(10, 5, 5, 5), spacing=3 ) # Button camera_button = UiElement.button( master_layout, ['Load Camera', 'Take Picture', 'Reset Camera'], [(0, 40), ] * 3, margin=(5, 5, 5, 5), spacing=3, vector='H' ) for button, action in zip(camera_button, [self.load_camera, self.take_picture, self.reset_camera]): button.clicked.connect(action) # Slider self.clip_opacity = UiElement.slider( master_layout, ['Camera Clip Opacity'], [(0, 0, 50)], margin=(5, 5, 5, 5), vector='H', )[0] self.clip_opacity.setTickInterval(1.0) self.clip_opacity.setMinimum(0.0) self.clip_opacity.setMaximum(1000.0) self.clip_opacity.setSliderPosition(1000.0) self.clip_opacity.valueChanged.connect(self.clip_value_changed) # Scene Widget self.graphic_widget, self.scene_widget = GraphicWidget.scene_widget(master_layout, margin=(5, 5, 5, 5)) self.graphic_widget.setFrameStyle(0) self.square = Square(20, rgba=(0, .7, .7, .3), action=True) self.scene_widget.addItem(self.square) self.square.setZValue(0) self.square.itemChanged.connect(self.camera_move) self.square.mouseRightClicked.connect(self.mouseRightClic) self.square.mouseRightRelease.connect(self.mouseRightRelease)
def hook_text_changed_event(maya_text_field, event): ptr = MQtUtil.findControl(maya_text_field) qt_wrapper = wrapInstance(long(ptr), QTextEdit) signal = QtCore.SIGNAL("textChanged(const QString&)") qt_wrapper.connect(signal, event) return qt_wrapper
def main_window(): window_ptr = MQtUtil.mainWindow() return wrapInstance(long(window_ptr), QtWidgets.QWidget)
def build_workspace_control_ui(shotgun_panel_name): """ Embeds a Shotgun app panel into the calling Maya workspace control. This function will be called in two cases: - When the workspace control is being created by Maya command workspaceControl; - When the workspace control is being restored from a workspace control state created by Maya when this workspace control was previously closed and deleted. .. note:: This function is only for Maya 2017 and later. :param shotgun_panel_name: Name of the Qt widget at the root of a Shotgun app panel. """ from maya.OpenMayaUI import MQtUtil # In the context of this function, we know that we are running in Maya 2017 and later # with the newer versions of PySide and shiboken. from PySide2 import QtWidgets from shiboken2 import wrapInstance import sgtk.platform # Retrieve the Maya engine. engine = sgtk.platform.current_engine() # Retrieve the calling Maya workspace control. ptr = MQtUtil.getCurrentParent() workspace_control = wrapInstance(long(ptr), QtWidgets.QWidget) # Search for the Shotgun app panel widget. for widget in QtWidgets.QApplication.allWidgets(): if widget.objectName() == shotgun_panel_name: maya_panel_name = workspace_control.objectName() engine.logger.debug( "Reparenting Shotgun app panel %s under Maya workspace panel %s.", shotgun_panel_name, maya_panel_name, ) # When possible, give a minimum width to the workspace control; # otherwise, it will use the width of the currently displayed tab. # Note that we did not use the workspace control "initialWidth" and "minimumWidth" # to set the minimum width to the initial width since these values are not # properly saved by Maya 2017 in its layout preference files. # This minimum width behaviour is consistent with Maya standard panels. size_hint = widget.sizeHint() if size_hint.isValid(): # Use the widget recommended width as the workspace control minimum width. minimum_width = size_hint.width() engine.logger.debug( "Setting Maya workspace panel %s minimum width to %s.", maya_panel_name, minimum_width, ) workspace_control.setMinimumWidth(minimum_width) else: # The widget has no recommended size. engine.logger.debug( "Cannot set Maya workspace panel %s minimum width.", maya_panel_name ) # Reparent the Shotgun app panel widget under Maya workspace control. widget.setParent(workspace_control) # Add the Shotgun app panel widget to the Maya workspace control layout. workspace_control.layout().addWidget(widget) # Install an event filter on Maya workspace control to monitor # its close event in order to reparent the Shotgun app panel widget # under Maya main window for later use. engine.logger.debug( "Installing a close event filter on Maya workspace panel %s.", maya_panel_name, ) panel_util.install_event_filter_by_widget( workspace_control, shotgun_panel_name ) # Delete any leftover workspace control state to avoid a spurious deletion # of our workspace control when the user switches to another workspace and back. if cmds.workspaceControlState(maya_panel_name, exists=True): # Once Maya will have completed its UI update and be idle, # delete the leftover workspace control state. engine.logger.debug( "Deleting leftover Maya workspace control state %s.", maya_panel_name, ) maya.utils.executeDeferred( cmds.workspaceControlState, maya_panel_name, remove=True ) break else: # The Shotgun app panel widget was not found and needs to be recreated. # Search for the Shotgun app panel that needs to be restored # among the panels registered with the engine. for panel_id in engine.panels: # The name of the Qt widget at the root of the Shotgun app panel # was constructed by prepending to the panel unique identifier. if shotgun_panel_name.endswith(panel_id): # Once Maya will have completed its UI update and be idle, # recreate and dock the Shotgun app panel. maya.utils.executeDeferred(engine.panels[panel_id]["callback"]) break else: # The Shotgun app panel that needs to be restored is not in the context configuration. engine.logger.error( "Cannot restore %s: Shotgun app panel not found. " "Make sure the app is in the context configuration. ", shotgun_panel_name, )
def hook_key_changed_event(maya_text_field, event): ptr = MQtUtil.findControl(maya_text_field) qt_wrapper = wrapInstance(long(ptr), QTextEdit) signal = QtCore.SIGNAL("keyReleaseEvent(QKeyEvent * ev)") qt_wrapper.connect(signal, event) return qt_wrapper
def get_maya_window(): '''Get Maya MainWindow as a QWidget.''' ptr = long(MQtUtil.mainWindow()) return shiboken.wrapInstance(ptr, QtGui.QMainWindow)
def __init__(self): # Set Window main_window = long(MQtUtil.mainWindow()) parent = wrapInstance (main_window, QtGui.QWidget) super(SkinToolsUI, self).__init__(parent) self.setWindowTitle("Deformer Utils") master_widget = QtGui.QWidget() master_layout = UiElement.base_layout(self) master_widget.setLayout(master_layout) self.setCentralWidget(master_widget) # Class variables self.path_role = QtCore.Qt.UserRole # Text Infos self.skin_infos = UiElement.textField( master_layout, ["Shape", "SkinCluster"], [(200, 0, 30), ] * 2, margin=(5, 5, 5, 5) ) for text_field in self.skin_infos: text_field.setFrame(False) self.skin_infos[0].returnPressed.connect(self.shapeTextEdited) self.skin_infos[1].returnPressed.connect(self.skinTextEdited) # List Animation tree_layout = UiElement.base_layout(master_layout, vector="H", spacing=5, margin=(5, 5, 5, 5)) list_label, self.skin_list = UiElement.tree_view( tree_layout, ["Skin Instance", "Skin Influences"], [(200, 0), (0, 0)], margin=(0, 0, 0, 0), vector="H", editable=(False, True) ) self.skin_list[0].clicked.connect(self.influencesFromItem) self.skin_list[0].setIconSize(QtCore.QSize(30, 30)) self.skin_list[1].setIconSize(QtCore.QSize(20, 20)) self.skin_list[1].cModel.itemChanged.connect(self.jointItemEdited) # for skin_list in self.skin_list: # skin_list.setFrame(False) # Read / Write actions = [self.getSkinDatas, self.writeSkin] self.button_Read = UiElement.button( master_layout, ["Get Skin", "Write Skin"], [(200, 40), (0, 40)], vector="H", spacing=5, margin=(5, 5, 5, 1) ) for button, action in zip(self.button_Read, actions): button.clicked.connect(action) # Restore Skin actions = [self.restoreByAttributes, self.restoreByFile] button_Write = UiElement.button( master_layout, ["Restore By Attribute", "Restore By File"], [(200, 40), (0, 40)], vector="H", spacing=5, margin=(5, 1, 5, 5) ) for button, action in zip(button_Write, actions): button.clicked.connect(action)
# Create an instance of the button and display it. # button = MyButton() button.show() # A valid Maya control name has been automatically assigned # to the button. # buttonName = button.objectName() print('# ' + buttonName) # MyButton_368fe1d8-5bc3-4942-a1bf-597d1b5d3b83 # Losing our only reference to the button does not cause it to be # destroyed. # myButton = None # We can use the button's name to find it as a Maya control. # from maya.OpenMayaUI import MQtUtil from shiboken2 import wrapInstance ptr = MQtUtil.findControl(buttonName) foundControl = wrapInstance(long(ptr), QPushButton) # Print out the button's text. # print('# ' + foundControl.text()) # Push Me