在PySide中单击按钮时,从MainWindow打开New MainWindow,不立即关闭

时间:2015-02-02 18:07:47

标签: python pyqt pyside qt-designer

我正在学习python中的GUI编程。我正在使用Pyside框架。为了练习,我正在开发一个简单的应用程序,用户打开新窗口按钮被单击。我开发了相同的简单原型:

MainFile.py

from PySide import QtGui, QtCore
import Starter
import sys

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    starter = Starter.StartClass()
    starter.show()
    sys.exit(app.exec_())

Starter.py

from PySide import QtGui, QtCore
import start1_ui, pop_up

class StartClass(start1_ui.Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.click_button.clicked.connect(self.call_method)

    def call_method(self):
        print 'hey! I am Starter'
        pop = pop_up.PopupClass()
        pop.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        pop.show()

pop_up.py

from PySide import QtGui, QtCore
import popup_ui
class PopupClass(popup_ui.Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        #self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        print 'I am shown'

我已经使用pyside-uic将在qtDesigner中创建的* .ui文件转换为* .py。我没有放这些py文件,因为它们太大了。文件的结构为

start1_ui.py

from PySide import QtCore, QtGui
class Ui_MainWindow(QtGui.QMainWindow):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(437, 290)
        ## Much more code for setting various widget attribute as width. height 
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.click_button.setText(QtGui.QApplication.translate("MainWindow", "ClickMe", None, QtGui.QApplication.UnicodeUTF8))

popup_ui.py

class Ui_MainWindow(QtGui.QMainWindow):
    def setupUi(self, MainWindow):
        #setting up widgets here
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("MainWindow", "Finally, I am  opened", None, QtGui.QApplication.UnicodeUTF8))

现在当我点击starter.py中的按钮时,新的弹出窗口会打开,但会立即关闭。我尝试将属性用作QtCore.Qt.WA_DeleteOnClose 但它没有帮助?

我错过了什么地方?如何打开弹出窗口并使其在上面的代码中可见?

修改 从注释中,我们需要维护新窗口对象的引用,以便gc不会清除它。那么在我们运行代码之后,第一个窗口是如何保持不变的呢?

通过在列表中添加它来进行引用,它将创建多个窗口。我只需要创建窗口。并且父窗口关闭然后自动关闭弹出窗口。

如何在上面的代码中使用QtCore.Qt.WA_DeleteOnClose方法?

1 个答案:

答案 0 :(得分:0)

也许尝试将弹出窗口的父级设置为主窗口?在starter.py中,请尝试pop.show(self)而不是pop.show()

相关问题