Running a Qt program from the Canopy GUI

Problem

If you run a naive Qt application in the Canopy GUI (or in any IPython PyLab or Matplotlib environment), you are likely to get a complaint from QApplication that an event loop is already running.

Background

By default, Canopy's IPython panel runs in "PyLab" mode. IPython's Pylab mode and Matplotlib mode each starts an event loop for the IPython front end (in this case, Canopy), which allows you to interact at the IPython command line with your GUI, a very powerful feature.

Solution

Your Qt program must check whether a QApplication (event loop) already exists, and if it does, then use the existing one instead of trying to create a new one.

Here's an simple example which will run with or without Pylab.

import sys
from PySide import QtGui
app = QtGui.QApplication.instance()
standalone = app is None
if standalone:
    app = QtGui.QApplication(sys.argv)
wid = QtGui.QWidget()
wid.resize(250,150)
wid.setWindowTitle('Simple')
wid.show()
if standalone:
    sys.exit(app.exec_())
else:
    print "We're back with the Qt window still active"
Have more questions? Submit a request

Comments

  • Avatar
    Abraham Alonzo Velázquez

    Thanks!

Powered by Zendesk