Skip to content

Instantly share code, notes, and snippets.

@defTechAndrew
Last active June 14, 2024 00:08
Show Gist options
  • Save defTechAndrew/27add8add479d9f451ba5bc928657573 to your computer and use it in GitHub Desktop.
Save defTechAndrew/27add8add479d9f451ba5bc928657573 to your computer and use it in GitHub Desktop.
Base widget class for using Maya's MayaQWidgetDockableMixin class that handles showing and restoring of the UI.
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
import maya.cmds as cmds
import PySide2.QtWidgets as qtwidgets
import maya.OpenMayaUI as omui
class DockableMixinWidget(MayaQWidgetDockableMixin, qtwidgets.QWidget):
_instance = None
_show_kwargs = {} # see kwargs for setDockableParameters in mayaMixin.py
def __init__(self):
super(DockableMixinWidget, self).__init__()
self.setObjectName(f'dockable_mixin_{self.__class__.__name__}')
@classmethod
def restore(cls):
'''Logic for restoring widget to Maya's workspace.'''
workspace_control = omui.MQtUtil.getCurrentParent()
cls._instance = cls()
pointer = omui.MQtUtil.findControl(cls._instance.objectName())
omui.MQtUtil.addWidgetToMayaLayout(int(pointer), int(workspace_control))
@classmethod
def open(cls, delete_ui=False):
'''Show the UI and store UI Script for restoration.
Args:
delete_ui(bool): Remove existing UI and instantiate a fresh version. Use to test changes to the UI.
Returns:
DockableMixinWidget: instance of object
'''
if delete_ui and cmds.workspaceControl(f'dockable_mixin_{cls.__name__}WorkspaceControl', exists=True):
cmds.deleteUI(f'dockable_mixin_{cls.__name__}WorkspaceControl')
cls._instance = None
if cls._instance is None:
cls._instance = cls()
cls._instance.show(
dockable=True,
uiScript=f"import {cls.__module__}\n{cls.__module__}.{cls.__name__}.restore()",
**cls._show_kwargs)
return cls._instance
class ExampleWidget(DockableMixinWidget):
_show_kwargs = {'widthSizingProperty':'preferred', 'minWidth':300}
def __init__(self):
super(ExampleWidget, self).__init__()
self.setWindowTitle('Example Dockable Widget')
self.setLayout(qtwidgets.QVBoxLayout())
label = qtwidgets.QLabel('Example Label')
self.layout().addWidget(label)
button = qtwidgets.QPushButton('Example Button')
self.layout().addWidget(button)
# To show your subclass UI call open
# ExampleWidget.open()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment