Maya PySide Cheatsheet 2017

This is a working document where I write down my notes about using PySide for Maya, which may prove to be useful to others as well. I plan on adding more examples in the future.

Examples assume that the required packages are imported.

Import PySide2 or PySide?

# use PySide2 if available (Maya 2017+) otherwise PySide
    from PySide2.QtCore import *
    from PySide2.QtGui import *
    from PySide2.QtWidgets import *
    from PySide2 import __version__
    from shiboken2 import wrapInstance
except ImportError:
    from PySide.QtCore import *
    from PySide.QtGui import *
    from PySide import __version__
    from shiboken import wrapInstance

Common Methods

QMainWindow()  # create a window
QHBoxLayout()  # horizontal layout
QVBoxLayout()  # vertical layout
QPushButton()  # create button
QCheckBox()  # create checkbox
QSpacerItem()  # create spacer
QFont()  # create font


import OpenMayaUI as omui
omui.MQtUtil.findControl()  # find Qt control object

Example: Create a simple window parented to Maya

# import wrapInstance
    from shiboken2 import wrapInstance
except ImportError:
    from shiboken import wrapInstance

# get Maya's main window
def getMayaMainWindow():
    mayaMainWindowPtr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(mayaMainWindowPtr), QWidget)

mainWindow = getMayaMainWindow()

# create a new window parented to Maya's window
window = QMainWindow(mainWindow)
window.setWindowTitle("My Window")

# create and attach widget
mainWidget = QWidget()

# create and add layout
layout = QVBoxLayout(mainWidget)

# create button
button = QPushButton("Click me")

# finally, show the window

Example: Finding a control widget

# create a checkbox...
layout = QHBoxLayout()
checkbox = QCheckBox("Label")

# ... and find it again
ptr = omui.MQtUtil.findControl("MyCheckbox")
checkbox = shiboken.wrapInstance(long(ptr), QtGui.QCheckBox)
value = checkBox.isChecked()

Example: Boilerplate code for window

Write a comment