Python Qtconsole: QApp = QCoreApplication.instance() returns None on Linux and a valid QApplication on Windows

StackOverflow https://stackoverflow.com/questions/15752963

Question

I have software which has a GUI interface and a command line interface. What it should do is detect if it is being run in a qtconsole. If it is, it will not create a new QApplication and show the GUI in a non-blocking manner. After the script exists, there will be a cmd object where the user can interact with things on a lower level.

from PyQt4.QtCore import QCoreApplication
from PyQt4.Qt import QApplication
import sys

QApp = QCoreApplication.instance() 
new_qapp_bit = False
if QApp == None:
    print 'running without the qt console'
    new_qapp_bit = True
    QApp = QApplication(sys.argv)
else:
    print 'found the qt console'

cmd = MyCMDInterface(use_gui=True)

if new_qapp_bit
    sys.exit(QApp.exec_())

On windows this works perfectly, QCoreApplication.instance() returns a valid QApplication and everything goes according to plan, but on Linux and Mac it returns None. I've been hacking at this awhile, and I'm not seeing any answers.

Was it helpful?

Solution

The problem was I forgot the '--pylab=qt ' argument when I ran

ipython qtconsole --pylab=qt --color=Linux -c "%run main.py"

OTHER TIPS

I am guessing that in windows you are using an IDE or something to execute your code. With the provided example I always get a return value of None.

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt4.QtCore import QCoreApplication
>>> from PyQt4.Qt import QApplication
>>> import sys
>>>
>>> QApp = QCoreApplication.instance()
>>> new_qapp_bit = False
>>> if QApp == None:
...     print 'running without the qt console'
...     new_qapp_bit = True
...     QApp = QApplication(sys.argv)
... else:
...     print 'found the qt console'
running without the qt console

There is a misconception here, trying to determine from the kernel wether not not you are running from the qtconsole make no sens. And --pylab=qt just run integration with a event loop. It would be like asking a Developer if his website was written in Firefox or Internet Explorer. In he same way you can visit the website with multiple browser, with IPython you can connect to the kernel with multiple client (console, qtconsole, notebook, emacs...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top