How to get maya main window pointer using PySide?

ninhenzo64 picture ninhenzo64 · Mar 11, 2014 · Viewed 8.7k times · Source

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?

Answer

qurban picture qurban · Mar 11, 2014

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.