PyQt window closes after launch

前端 未结 2 657
一向
一向 2021-01-17 03:53

I\'m trying to use a QPushButton to call a function that opens a new instance of QWebView. Works but as soon as the window opens it closes again. I\'ve read this - PyQt win

2条回答
  •  孤街浪徒
    2021-01-17 04:58

    To keep a reference to a QObject, you can either keep the variable in scope, or add it as the child of another QObject which variable already stays in scope.

    And for QWidget, the parent should also be a QWidget, so, in your case, you'd want to make w as the parent of all your QMainWindows.

    def web1(parent):
        ...
        class Browser(QtGui.QMainWindow): # "Browser" window
            def __init__(self, parent):
                QtGui.QMainWindow.__init__(self, parent)
                ...
    
    def main():
        ...
        w.__button.clicked.connect(lambda: web1(w))
    

    This also avoid maintaining manually a list of opened windows, since the object hierarchy can do that for you.

    PS: The child windows are shown as toplevel windows and not inside the w window, because QMainWindow (and QDialog) has the Qt::Window flag set by default.

提交回复
热议问题