PyQt thread still running after window closed

空扰寡人 提交于 2019-12-24 13:33:31

问题


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.



来源:https://stackoverflow.com/questions/33701243/pyqt-thread-still-running-after-window-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!