编程语言
首页 > 编程语言> > python – PyQt:如何隐藏QMainWindow

python – PyQt:如何隐藏QMainWindow

作者:互联网

单击Dialog_01的按钮隐藏其窗口并打开Dialog_02.单击Dialog_02的按钮应关闭其窗口并取消隐藏Dialog_01.怎么实现呢?

import sys, os
from PyQt4 import QtCore, QtGui    

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

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()       

        Button_02 = QtGui.QPushButton("Close THIS and Unhide Dialog 01")
        Button_02.clicked.connect(self.closeAndReturn)
        myBoxLayout.addWidget(Button_02)

        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)
        self.setWindowTitle('Dialog 02')

    def closeAndReturn(self):
        self.close()

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

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()       

        Button_01 = QtGui.QPushButton("Hide THIS and Open Dialog 02")
        Button_01.clicked.connect(self.callAnotherQMainWindow)
        myBoxLayout.addWidget(Button_01)        

        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)
        self.setWindowTitle('Dialog 01')

    def callAnotherQMainWindow(self):
        self.hide()
        self.dialog_02 = Dialog_02()
        self.dialog_02.show()
        self.dialog_02.raise_()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    sys.exit(app.exec_())

解决方法:

使第一个窗口成为第二个窗口的父窗口:

class Dialog_02(QtGui.QMainWindow):
    def __init__(self, parent):
        super(Dialog_02, self).__init__(parent)
        # ensure this window gets garbage-collected when closed
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
    ...    

    def closeAndReturn(self):
        self.close()
        self.parent().show()

class Dialog_01(QtGui.QMainWindow):
    ...

    def callAnotherQMainWindow(self):
        self.hide()
        self.dialog_02 = Dialog_02(self)
        self.dialog_02.show()

如果您希望每次都显示相同的对话框,请执行以下操作:

    def callAnotherQMainWindow(self):
        self.hide()
        if not hassattr(self, 'dialog_02'):
            self.dialog_02 = Dialog_02(self)
        self.dialog_02.show()

并隐藏()子窗口,而不是关闭它.

标签:python,pyqt,qtgui,qmainwindow
来源: https://codeday.me/bug/20190624/1279536.html