Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Kernel crashes after closing an PyQt4 Gui Application

Ok here is my problem:

I want to create a PyQt4 Gui, which can be executed from a python console (tested with IDLE, Spyder Console and IPython Console) and then allows the user to change and view variables. After closing the app the user should be able to do further work with the variables in the console. But by closing the Gui the Kernel crashes and it is not possible to make any new input to the console.

I'm working with Python 2.7 and PyQt4. I am using the following code to start an close the application:

app=QtGui.QApplication(sys.argv)
MainApp=plottest()
MainApp.show()
sys.exit(app.exec_())
like image 404
arthaigo Avatar asked Jun 04 '14 15:06

arthaigo


2 Answers

The easy solution here https://www.reddit.com/r/learnpython/comments/45h05k/solved_kernel_crashing_when_closing_gui_spyder/

only put

if __name__ == "__main__":
    app=0           #This is the solution
    app = QtGui.QApplication(sys.argv)
    MainApp = Dice_Roller()
    MainApp.show()
    sys.exit(app.exec_())
like image 62
Gabriel Asqui Avatar answered Oct 14 '22 00:10

Gabriel Asqui


What you need to do is:

  1. Check that there isn't already a QApplication instance when trying to create a new one
  2. Ensure that the QApplication object is deleted after it's been closed

(See simple IPython example raises exception on sys.exit())

# Check if there's a pre-existing QApplication instance 
# If there is, use it. If there isn't, create a new one.
app = QtGui.QApplication.instance()
if not app:
    app = QtGui.QApplication(sys.argv)

# Ensure that the app is deleted when we close it
app.aboutToQuit.connect(app.deleteLater)

# Execute the application
MainApp = plottest()
MainApp.show()
sys.exit(app.exec_())

Using this code you can rerun the application as many times as you want in IPython, or anywhere else. Every time you close your Qt application, the app object will be deleted in python.

like image 32
hdunn Avatar answered Oct 14 '22 00:10

hdunn