【问题标题】:How to get maya main window pointer using PySide?如何使用 PySide 获取 Maya 主窗口指针?
【发布时间】:2014-03-11 16:52:21
【问题描述】:

我在 Maya 中使用过很多 PyQt4,通常我发现切换到 PySide 很容易,但我无法获得指向主窗口的指针。也许有人可以理解出了什么问题。

这是我在 PyQt4 中所做的:

import sip, PyQt4.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mainWindow()
parent = sip.wrapinstance(long(ptr), PyQt4.QtCore.QObject)

这很好用。当我在 PySide 中尝试相同的操作时:

import sip, PySide.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mainWindow()
parent = sip.wrapinstance(long(ptr), PySide.QtCore.QObject)

我收到以下错误:

# 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 # 

有人知道怎么回事吗?

【问题讨论】:

    标签: python pyqt pyside maya


    【解决方案1】:

    您需要导入shiboken 而不是sip 并将QWidget 传递给wrapInstance 而不是QObject

    编辑: Maya2017 包含 shiboken2PySide2 而不是 shibokenPySide,如下面的 cmets 中指出的那样。

    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)
    

    请注意sipwrapinstance,其中i 不是大写,而shiboken.wrapInstance i 是大写。

    shiboken.wrapInstance() 需要 wrapertype 作为第二个参数,因此您可以将 QWidget 作为第二个参数传递。

    【讨论】:

    • shiboken 在 Maya 2017 上不可用。人们现在使用它来获取主窗口链接:对于 QtWidgets.qApp.topLevelWidgets() 中的 obj... 然后检查是否有 objectName() == '玛雅窗口' 。别忘了 PySide 现在是 PySide2
    • shiboken 现在是 shiboken2。目前,shiboken2 没有记录在 Maya2017 官方文档中。
    【解决方案2】:

    因为之前的答案已经有些过时了,所以这里有一个更新的版本,可以省去必须自己更新的麻烦。

    获取maya主窗口的两种方法:

    • 使用 PySide2:
    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())
    
    • 使用 shiboken2 和 maya api:
    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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多