按代码创建 PyQt 窗口

在这个例子中,我们尝试仅使用代码而不是使用任何 ui 文件来创建 gui。这是一个非常基本的例子,你需要根据自己的需要进行扩展。“

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

class Ui_MainWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.centralwidget = QtGui.QWidget(self)
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(80, 50, 75, 23))
        self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(190, 50, 111, 151))
        self.pushButton_3 = QtGui.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(350, 60, 75, 101))
        self.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(self)
        self.setStatusBar(self.statusbar)
        self.retranslateUi()

    def retranslateUi(self):
        self.setWindowTitle("MainWindow")
        self.pushButton.setText("test")
        self.pushButton_2.setText( "test")
        self.pushButton_3.setText("test")

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

def mayaMain():
    global maya_basicTest_window
    try:
        maya_basicTest_window.close()
    except:
        pass
    maya_basicTest_window = Ui_MainWindow(getMayaWindow())
    maya_basicTest_window.show()

mayaMain()