PyQt thread still running after window closed

2019-08-11 11:25发布

问题:

When I close an application window in PyQt the console is still left running in the background and python.exe process is present until I close the console. I think the sys.exit(app.exec_()) is not able to operate properly.

Mainscript (which opens Firstwindow):

if __name__ == '__main__':
    from firstwindow import main
    main()

Firstwindow

On button press:

    self.close() #close firstprogram
    Start() #function to open mainprogram

Start():

def Start():
        global MainWindow
        MainWindow = QtWidgets.QMainWindow()
        ui = genui_MainWindow()
        ui.setupUi(MainWindow)
        MainWindow.show()

main() (suggested here):

def main_window():
     return form

def main():
    global form
    app = QtWidgets.QApplication(sys.argv)  
    form = MyApp()  
    form.show()
    app.exec_()
    sys.exit(app.exec_())

回答1:

The problem is that you are calling exec_() twice in the main() function:

def main():
    global form
    app = QtWidgets.QApplication(sys.argv)  
    form = MyApp()  
    form.show()
    app.exec_()
    sys.exit(app.exec_())

The first app.exec_() line will start an event-loop, which means the main() function will pause there while you interact with the gui. When you close the top-level window (or call quit() on the application), the event-loop will stop, exec_() will return, and the main() function will continue.

But the next line calls sys.exit(app.exec_()), which restarts the event-loop, and pauses the main() function again - including the sys.exit() call, which must wait for exec_() to return. However, it will wait forever, because there is now no gui to interact with, and so there's nothing you can to do to stop the event-loop other than forcibly terminating the script.