将Pyside qt4脚本转换为pyside2 qt5:我的导入在哪里失败?

问题描述:

我试图将旧的玛雅python脚本转换为Maya 2017.在2017年,他们做了一些更改,包括从PySide切换到PySide 2和Qt4到Qt5。我对这些库甚至Python都没有经验。将Pyside qt4脚本转换为pyside2 qt5:我的导入在哪里失败?

我做的第一件事就是尝试通过pyqt4topyqt5运行它,但没有检测到必要的更改。

我相信这两个版本的脚本的核心功能是一样的,但是由于这些改变,GUI加载失败。原来的剧本导入库如下:

import shiboken 
from PySide import QtGui 
import maya.OpenMayaUI as apiUI 
from cStringIO import StringIO 
import pysideuic 
import xml.etree.ElementTree as xml 

def get_maya_window(): 

    ptr = apiUI.MQtUtil.mainWindow() 
    if ptr is not None: 
     return shiboken.wrapInstance(long(ptr), QtGui.QMainWindow) 

def load_ui_type(ui_file): 

    parsed = xml.parse(ui_file) 
    widget_class = parsed.find('widget').get('class') 
    form_class = parsed.find('class').text 
    with open(ui_file,'r') as f: 
     o = StringIO() 
     frame = {} 

     pysideuic.compileUi(f, o, indent = 0) 
     pyc = compile(o.getvalue(), '<string>', 'exec') 
     exec pyc in frame 

     # Fetch the base_class and form class based on their type in the xml from design 
     form_class = frame['Ui_{0}'.format(form_class)] 
     base_class = eval('QtGui.{0}'.format(widget_class)) 

    return form_class, base_class 

我改变PySide的所有实例PySide2,shiboken到shiboken2(在Maya 2017年的另一个变化),并pysideuic到pyside2uic。当测试脚本,我得到了错误

Error: line 1: AttributeError: file <string> line 1: 'module' object has no attribute 'QMainWindow' # 

(1号线指的是在另一个脚本行:

from JUM.core.loadUIFile import get_maya_window, load_ui_type 

调用该文件)

通过QT5文档后一看,我确定QMainWindow现在是包含在PyQt5中的QtWidgets的一部分,而不是QtGui,所以我也替换了它。目前脚本代码是

import shiboken2 
from PyQt5 import QtWidgets 
import maya.OpenMayaUI as apiUI 
from cStringIO import StringIO 
import pyside2uic 
import xml.etree.ElementTree as xml 

def get_maya_window(): 

    ptr = apiUI.MQtUtil.mainWindow() 
    if ptr is not None: 
     return shiboken2.wrapInstance(long(ptr), QtWidgets.QMainWindow) 

def load_ui_type(ui_file): 

    parsed = xml.parse(ui_file) 
    widget_class = parsed.find('widget').get('class') 
    form_class = parsed.find('class').text 
    with open(ui_file,'r') as f: 
     o = StringIO() 
     frame = {} 

     pyside2uic.compileUi(f, o, indent = 0) 
     pyc = compile(o.getvalue(), '<string>', 'exec') 
     exec pyc in frame 

     # Fetch the base_class and form class based on their type in the xml from design 
     form_class = frame['Ui_{0}'.format(form_class)] 
     base_class = eval('QtWidgets.{0}'.format(widget_class)) 

    return form_class, base_class 

但是我仍然得到完全相同的错误,所以我认为我的模块导入有问题。任何人都可以在Python中使用Qt5的知识吗?

+1

当然,您需要从PySide2导入,而不是PyQt5? – ekhumoro

+0

@ekhumoro我也尝试过,结果完全一样。 – mlamp

+0

您可以通过手动丢弃所有不需要的错误来显示。 – Trilarion

简单的答案就是这个。 QTWidgets不是QTGui。在Pyside2中,您不仅会导入shiboken2和wrapinstance2,而且还会导入QTWidgets

def get_maya_window(): 

    ptr = apiUI.MQtUtil.mainWindow() 
    if ptr is not None: 
     return shiboken2.wrapInstance2(long(ptr), QtWidgets.QWidget)