一个QApplication实例已经存在。

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监听器上使用时才会出现错误。

3个回答

12

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

通常在脚本中使用 QtGui.QApplication() 创建 PySide 应用程序对象。然而,在3ds Max中,已经有一个 PySide 应用程序正在运行,所以您可以通过以下方式获取该对象的句柄:

QtGui.QApplication.instance()

1
这已经不再适用于Max 2018,查看我的Area帖子[此处](https://forums.autodesk.com/t5/3ds-max-programming/3ds-max-2018-pyside-issues/m-p/7474544#M17145) - Spencer

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()

2
你正在这行代码中创建一个 QApplication 的实例:
app = QApplication(sys.argv)

由于在“3Dsmax 2015 Listener”中先前创建了另一个QApplication实例,因此出现了该错误,而您只允许一个实例。
请参见:
QT文档上的链接1:QApplication

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接