简体   繁体   中英

Python PyQt4: Single child window

I have a simple PyQt4 example.
When run, it displays a QMainWindow with a button. If you click the button, then a second QMainWindow is created. If you click it again, you get 2 second windows.

What is an elegant and simple way to prevent more than 1 second window in this example?

import sys
from PyQt4.QtGui import *

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

        layout = QVBoxLayout()

        label = QLabel(self)
        label.setText('This is win2')
        layout.addWidget(label)

        self.adjustSize()

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        layout = QVBoxLayout()

        button1 = QPushButton("win2", self)
        layout.addWidget(button1)

        button1.clicked.connect(self.showwin2) 

    def showwin2(self):
        w2 = win2(self)
        w2.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())

Your Function creates a new instance of the class win2 each time the button is pressed. To Supress this behavior only call the show and raise_ functions instead of creating a new instance.

I would create the class as follows, and only use the button to 'show' the window. Tested and works as intended. Also consider using self when assigning your variables so they can be accessed throughout the class instance.

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        layout = QVBoxLayout()

        button1 = QPushButton("win2", self)
        layout.addWidget(button1)
        button1.clicked.connect(self.showwin2) 
        self.w2 = win2(self)

     def showwin2(self):
        self.w2.show()
        self.w2.raise_()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM