Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Kill PyQT Window after closing it. Which requires me to restart the kernal

I guess that I am not closing my PyQT5 Window correctly. I am using spyder (3.3.5) which I have installed with anaconda, to program a pyqt5 program. I am using qt creator to design my ui file, which I load using the loadUi function in pyqt package. Everything works fine with the code, until I need to close it. I close the window via the close button (the x button in the top right). The window itself is closed, but it seems like the console (or shell) is stuck, and I can't give it further commands or to re run the program, without having to restart the kernel (to completely close my IDE and re opening it).

I have tried looking for solutions to the problem in the internet, but none seems to work for me. Including changing the IPython Console > Graphics to automatic.

Edit: Also Created an issure: https://github.com/spyder-ide/spyder/issues/9991

import sys
from PyQt5 import QtWidgets,uic
from PyQt5.QtWidgets import QMainWindow
class Mic_Analysis(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui=uic.loadUi("qt_test.ui",self)
...
if __name__ == "__main__":
    def  run_app():
        if not QtWidgets.QApplication.instance():        
            app = QtWidgets.QApplication(sys.argv)
        else:
            app=QtWidgets.QApplication.instance()
        mainWin=Mic_Analysis()
        mainWin.show()
        app.exec_()
    run_app()  

If someone have any suggestion I would be very happy to hear them.

like image 431
mashtock Avatar asked Oct 25 '25 04:10

mashtock


2 Answers

For me, it helped to remove the 'app.exec_()' command. But then it closes immediatly when running the code. To keep the window open, I needed to return the MainWindow instance to the global scope (or make it a global object). My code looks like this:

from PyQt5 import QtWidgets
import sys

def main():
    if not QtWidgets.QApplication.instance():
        app = QtWidgets.QApplication(sys.argv)
    else:
        app = QtWidgets.QApplication.instance()
    main = MainWindow()
    main.show()

    return main

if __name__ == '__main__':         
    m = main()
like image 165
luckycharly Avatar answered Oct 27 '25 18:10

luckycharly


Try adding :

app.setQuitOnLastWindowClosed(True)

to your main() function

def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)    
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())
like image 36
Sam Gomari Avatar answered Oct 27 '25 18:10

Sam Gomari