Maya + PyQt 对话框。如何运行 Qt的单个副本window?

Maya + PyQt dialog. How to run a single copy of Qt window?

使用这个简单的代码 运行 a window 基于 qdialog:

import maya.OpenMayaUI as mui
import sip
from PyQt4 import QtGui, QtCore, uic

#----------------------------------------------------------------------
def getMayaWindow():
    ptr = mui.MQtUtil.mainWindow()
    return sip.wrapinstance(long(ptr), QtCore.QObject)

#----------------------------------------------------------------------
form_class, base_class = uic.loadUiType('perforceBrowserWnd.ui')

#----------------------------------------------------------------------
class PerforceWindow(base_class, form_class):
    def __init__(self, parent=getMayaWindow()):
        super(base_class, self).__init__(parent)
        self.setupUi(self)

#----------------------------------------------------------------------
def perforceBrowser2():
    perforceBrowserWnd = PerforceWindow()
    perforceBrowserWnd.show()

perforceBrowser2()

每次您 运行 函数 perforceBrowser2() 都会有一个新副本 windows。

如何判断一个window是否已经运行ning而不是打开一个新的副本,并转到打开的window?或者只是不给脚本 运行 window 的第二个副本?

ps。 maya2014 + pyqt4 + python2.7

保留对 window:

的全局引用
perforceBrowserWnd = None

def perforceBrowser2():
    global perforceBrowserWnd
    if perforceBrowserWnd is None:
        perforceBrowserWnd = PerforceWindow()
    perforceBrowserWnd.show()

使用 global 不是首选方式,有很多文章说明它不是一个好主意。

Why are global variables evil? It is cleaner to remember the instance in a static var of the class and whenever you load the UI, check if it does already exist and return it, if not create it. (There is a pattern called Singleton that describes this behaviour as well)

import sys

from Qt import QtGui, QtWidgets, QtCore

class Foo(QtWidgets.QDialog):
    instance = None
    def __init__(self, parent=None):
        super(Foo, self).__init__(parent)
        self.setWindowTitle('Test')

def loadUI():
    if not Foo.instance:
        Foo.instance = Foo()
    Foo.instance.show()
    Foo.instance.raise_()

loadUI()

无论何时您调用加载UI,它都会return相同的UI并且不会在您每次调用它时重新创建。