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.

Examples assume that the required packages are imported.

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

Import PySide2 or PySide?

# use PySide2 if available (Maya 2017+) otherwise PySide
try:
    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

Example: Create a simple window parented to Maya

# import wrapInstance
try:
    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.setObjectName("MyWindow")
window.setWindowTitle("My Window")

# create and attach widget
mainWidget = QWidget()
window.setCentralWidget(mainWidget)

# create and add layout
layout = QVBoxLayout(mainWidget)

# create button
button = QPushButton("Click me")
layout.addWidget(button)

# finally, show the window
window.show()

Example: Finding a control widget

# create a checkbox...
layout = QHBoxLayout()
checkbox = QCheckBox("Label")
checkbox.setObjectName("MyCheckbox")
checkbox.setChecked(True)
layout.addWidget(checkbox)

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