I've used PyQt4 in maya quite a bit, and generally I've found it quite easy to switch to PySide, but I'm having trouble getting the pointer to the main window. Perhaps someone can understand what's going wrong.
Here's what I do in PyQt4:
import sip, PyQt4.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mainWindow()
parent = sip.wrapinstance(long(ptr), PyQt4.QtCore.QObject)
This works fine. When I try the same in PySide:
import sip, PySide.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mainWindow()
parent = sip.wrapinstance(long(ptr), PySide.QtCore.QObject)
I get the following error:
# Error: wrapinstance() argument 2 must be sip.wrappertype, not Shiboken.ObjectType
# Traceback (most recent call last):
# File "<maya console>", line 4, in <module>
# TypeError: wrapinstance() argument 2 must be sip.wrappertype, not Shiboken.ObjectType #
Anyone know what's going wrong?
You need to import shiboken
instead of sip
and pass QWidget
to wrapInstance
instead of QObject
Edit: Maya2017 contains shiboken2
and PySide2
instead of shiboken
and PySide
as pointed out in comments below.
import shiboken
from PySide import QtGui, QtCore
import maya.OpenMayaUI as apiUI
def getMayaWindow():
"""
Get the main Maya window as a QtGui.QMainWindow instance
@return: QtGui.QMainWindow instance of the top level Maya windows
"""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return shiboken.wrapInstance(long(ptr), QtGui.QWidget)
Please note that sip
has wrapinstance
in which i is not capital but in shiboken.wrapInstance
i is capital.
shiboken.wrapInstance()
requires wrapertype as a second argument, so you can pass QWidget
as a second argument.
Because the previous answer has become somewhat out-of-date, here is a more current version to save someone the trouble of having to update it themselves.
Two approaches for getting the maya main window:
from PySide2 import QtWidgets
global app
app = QtWidgets.QApplication.instance() #get the qApp instance if it exists.
if not app:
app = QtWidgets.QApplication(sys.argv)
def getMayaMainWindow():
mayaWin = next(w for w in app.topLevelWidgets() if w.objectName()=='MayaWindow')
return mayaWin
print(getMayaMainWindow())
import maya.OpenMayaUI as apiUI
from PySide2 import QtWidgets
try:
import shiboken2
except:
from PySide2 import shiboken2
def getMayaMainWindow():
ptr = apiUI.MQtUtil.mainWindow()
mayaWin = shiboken2.wrapInstance(long(ptr), QtWidgets.QWidget)
return mayaWin
print(getMayaMainWindow())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With