简体   繁体   English

Python PyQt4:单子窗口

[英]Python PyQt4: Single child window

I have a simple PyQt4 example. 我有一个简单的PyQt4示例。
When run, it displays a QMainWindow with a button. 运行时,它将显示带有按钮的QMainWindow。 If you click the button, then a second QMainWindow is created. 如果单击该按钮,则会创建第二个QMainWindow。 If you click it again, you get 2 second windows. 如果再次单击它,将显示2秒窗口。

What is an elegant and simple way to prevent more than 1 second window in this example? 在此示例中,有什么优雅而简单的方法可以防止超过1秒的窗口出现?

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. 每次按下按钮,您的Function都会创建类win2的新实例。 To Supress this behavior only call the show and raise_ functions instead of creating a new instance. 要抑制此行为,请仅调用show和raise_函数,而不创建新实例。

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. 在分配变量时也请考虑使用self,以便可以在整个类实例中对其进行访问。

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_()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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