为什么小部件会立即关闭?

Why does widget close instantly?

我正在尝试让在 Qt 设计器中创建的小部件在不同的脚本中从我的 QMainWindow class 的菜单选项中调用。到目前为止,它只是立即退出。我想知道是否有人可以告诉我我做错了什么?我需要调用子流程吗?

以下是脚本的相关部分:

主要脚本:

import sys
from PyQt4 import QtGui
from lib import Step1_Import_data

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow,self).__init__()

        openEditor = QtGui.QAction("&Editor",self)
        openEditor.setShortcut("Ctrl+E")
        openEditor.triggered.connect(self.editor)

        self.statusBar()
        mainMenu = self.menuBar()
        editorMenu = mainMenu.addMenu('&Editor')
        editorMenu.addAction(openEditor)
        self.showMaximized()

    def editor(self):
        Form = QtGui.QWidget()
        ui = Step1_Import_Data.Ui_Form()
        widget = ui.setupUi(Form)
        Form.show()
        self.setCentralWidget(widget)

def main():
    app = QtGui.QApplication(sys.argv)    
    GUI = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

然后这是我的脚本Step1_Import_Data.py

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(826, 536)
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(680, 10, 131, 41))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        """
        Loads more stuff...
        """

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

   def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "Step 2: Data Checking", None))

        """
        More stuff redacted to be concise
        """

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

您需要保留对子 window 的引用,否则当函数 returns:

时它将立即被垃圾回收
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        ...
        self.editorWindow = None            

    def editor(self):
        if self.editorWindow is None:
            self.editorWindow = EditorWindow()
        self.editorWindow.show()

class EditorWindow(QtGui.QWidget):
    def __init__(self):
        super(EditorWindow, self).__init__()
        self.ui = Step1_Import_data.Ui_Form()
        self.ui.setupUi(self)