PyQt and PySide Widget Best Practices

 
 
 

Maintain a Reference to your Widget

If you are using PyQt or PySide to customize Maya's user interface, you should make sure to parent your widget under an existing Maya widget, such as Maya's main window. Otherwise, if the widget is un-parented, it may be destroyed by the Python interpreter's garbage collector if a reference to it is not maintained.

The following code sample exemplifies this best practice. Note that this code will also work by importing the PyQt module instead of PySide.

from maya import OpenMayaUI as omui 
from PySide.QtCore import * 
from PySide.QtGui import * 
from shiboken import wrapInstance 

mayaMainWindowPtr = omui.MQtUtil.mainWindow() 
mayaMainWindow= wrapInstance(long(mayaMainWindowPtr), QWidget) 

# WORKS: Widget is fine 
hello = QLabel("Hello, World", parent=mayaMainWindow) 
hello.setObjectName('MyLabel') 
hello.setWindowFlags(Qt.Window) # Make this widget a standalone window even though it is parented 
hello.show() 
hello = None # the "hello" widget is parented, so it will not be destroyed. 

# BROKEN: Widget is destroyed 
hello = QLabel("Hello, World", parent=None) 
hello.setObjectName('MyLabel') 
hello.show() 
hello = None # the "hello" widget is not parented, so it will be destroyed.
NoteThe PySide, PyQt, and shiboken modules are not distributed with Maya and must be installed separately.