Over the last week I researched various GUI packages for Python and was trying to figure out what works best with Maya. The revelation struck me later that Maya comes built in with PySide, and I began to explore building a simple layout with a button, following a very helpful tutorial by Jeremy Ernst :
PySide UI Creation in Maya: Video One on Vimeo
In this video Jeremy explains the main components required to build a Maya interface. However, it's been 7 years and Maya has now updated to PySide2, with some minor changes. Having researched what to replace, I've decided to post my basic documentation of those changes as well as summarize the video!
First off: Multiple functions were shifted over to the QtWidgets class, so it has to be imported instead of or in addition to QtGui. Next: shiboken has now become shiboken2.
from PySide2 import QtWidgets, QtGui
import shiboken2
import maya.OpenMayaUI as mui
def getMayaWindow():
pointer = mui.MQtUtil.mainWindow()
return shiboken2.wrapInstance(int(pointer), QtWidgets.QWidget)
Understanding the code: This is our attempt to get a pointer to the Main Maya Window, and tie it to our layout window so that it does not disappear when we click outside it. Note: Python3 no longer uses the
long datatype, it is now
int. the
wrapInstance function serves as a wrapper for a C++ object by taking the pointer and the return type as arguments.
def createLocator():
maya.cmds.spaceLocator()
Just a little something for our button to do. Oh the rabbit hole I've been through with connecting buttons to functions.
parent = getMayaWindow()
window = QtWidgets.QMainWindow(parent)
widget = QtWidgets.QWidget()
window.setCentralWidget(widget)
layout = QtWidgets.QVBoxLayout(widget)
First we get the reference to Maya's main window, returned as a widget, and then we create our window with the Maya Main Window as its parent. This prevents it from being a separate window altogether that's hanging in space.
font = QtGui.QFont()
font.setPointSize(12)
button = QtWidgets.QPushButton("create Locator")
layout.addWidget(button)
button.setFont(font)
button.setMinimumSize(200,40)
button.setMaximumSize(200,40)
button.clicked.connect(createLocator)
window.show()
Finally, can create the button, add it to the widget, style it and add its function.
Buttons use signals and slots to handle their operations. A signal denotes the state of the button - has it been clicked, pressed, released or toggled? This signal triggers the slot based on the code. In this case, clicked is the signal, and the function createLocator is the slot.
No comments:
Post a Comment