7

我正在 3Dsmax 2015 上做一些简单的 PySide。

这是我的错误:

python.ExecuteFile "C:\Program Files\Autodesk\3ds Max 2015\scripts\Python\demoUniTest.py"
-- Runtime error:  Line 32  <module>()
  <type 'exceptions.RuntimeError'> A QApplication instance already exists.

这是我的代码:

import sys
from PySide.QtCore import *
from PySide.QtGui import *
from math import *

class Form(QDialog):
def __init__(self,parent=None):
    super(Form,self).__init__(parent)

    self.browser = QTextBrowser()
    self.lineedit = QLineEdit("Type an expression and press Enter")
    self.lineedit.selectAll()

    layout = QVBoxLayout()
    layout.addWidget(self.browser)
    layout.addWidget(self.lineedit)
    self.setLayout(layout)

    self.lineedit.setFocus()

    self.connect(self.lineedit, SIGNAL("returnPressed()"),self.updateUi)
    self.setWindowTitle("Calculate")

def updateUi(self):
    try:
        text = self.lineedit.text()
        self.browser.append("%s = <b>%s</b>" % (text,eval(text)))
    except:
        self.browser.append("<font color=red>%s is invalid</font>" %text)

app = QApplication(sys.argv)

form = Form()

form.show()

app.exec_()

当我在 Pycharm 上使用此代码时,我没有收到任何错误。只有当我在 3Dsmax 2015 Listener 上使用它时才会出现

4

3 回答 3

12

从帮助文件中直接引用(使用 PySide):

通常使用 QtGui.QApplication() 在脚本中创建一个 PySide 应用程序对象。但是,在 3ds Max 中,已经有一个 PySide 应用程序正在运行,因此您可以获得该对象的句柄,如下所示:

QtGui.QApplication.instance()
于 2014-11-26T14:32:31.167 回答
4

请注意,这在 3DS Max 2018 和 PySide2 中有所改变。我现在只是自己玩弄它,经过一些修补后我能够让它工作。这是文档的链接,但请注意代码中有一个小错字(至少在撰写本文时):http ://help.autodesk.com/view/3DSMAX/2018/ENU/?guid= __developer_what_s_new_in_3ds_max_python_api_what_s_new_in_the_3ds_max_2018_p_html

正如其他答案中提到的,您需要使您的 UI 成为主 3DS Max 应用程序的子级。好消息是他们已经为你简化了这个功能GetQMaxMainWindow()。像这样使用它:

from PySide2 import QtWidgets, QtCore, QtGui
import MaxPlus
import os

class SampleUI(QtWidgets.QDialog):
    def __init__(self, parent=MaxPlus.GetQMaxMainWindow()):
        super(SampleUI, self).__init__(parent)
        self.initUI()

    def initUI(self):
        mainLayout = QtWidgets.QHBoxLayout()
        testBtn = QtWidgets.QPushButton("Test!")
        mainLayout.addWidget(testBtn)
        self.setLayout(mainLayout)

if __name__ == "__main__":
    try:
        ui.close()
    except:
        pass

    ui = SampleUI()
    ui.show()
于 2017-10-14T00:27:01.843 回答
2

您正在以下行中创建 QApplication 的实例:

app = QApplication(sys.argv)

并得到该错误,因为在此之前某处创建了另一个 QApplication 实例(大概在“3Dsmax 2015 Listener”中的某处)并且您只被允许使用一个。

看:

QApplication 上的 QT 文档

于 2014-11-26T13:52:46.417 回答