[PyQt] how does qApp work in Python? (was Re: from PyQt5.Qt import *)

Christian Tismer tismer at stackless.com
Thu Jun 28 14:42:33 BST 2018

On 28.06.18 14:52, Kyle Altendorf wrote:
> On 2018-06-28 08:37, Christian Tismer wrote:
>> There is just a single exception that I built explicitly
>> into our new PySide2 version:
>> It allows to write "from PySide2 import *".
> Since this just came up recently in #pyqt, how do you handle qApp?  Same
> question for PyQt actually.  It didn't seem to be working as expected. 
> I also wouldn't expect it to work with the * imports in any case.
>     from PyQt5 import QtWidgets
>     class ObviouslyNewApp(QtWidgets.QApplication):
>         pass
>         def abc(self):
>             pass
>     print(QtWidgets.qApp)
>     app = ObviouslyNewApp([])
>     print(QtWidgets.qApp)
>     print(app)
>     print(app.abc)
>     print(QtWidgets.QApplication.instance().abc)
>     print(QtWidgets.qApp.abc)
> Which outputs:
>     <PyQt5.QtWidgets.QApplication object at 0x7fa70fd82ee8>
>     <PyQt5.QtWidgets.QApplication object at 0x7fa70fd82ee8>
>     <__main__.ObviouslyNewApp object at 0x7fa70fd82f78>
>     <bound method ObviouslyNewApp.abc of <__main__.ObviouslyNewApp
> object at 0x7fa70fd82f78>>
>     <bound method ObviouslyNewApp.abc of <__main__.ObviouslyNewApp
> object at 0x7fa70fd82f78>>
>     Traceback (most recent call last):
>       File "x.py", line 15, in <module>
>         print(QtWidgets.qApp.abc)
>     AttributeError: 'QApplication' object has no attribute 'abc'
> It seems that qApp would have to be a special attribute of the module or
> just be made callable instead to work properly in Python.  For
> reference, here's (one of?) the C++ macro definition(s).

Yes, I know that problem, and I worked quite heavily on it.

Not sure whether I was a bit too painstaking, but I thought
to mimic a macro as far as possible in Python.

Therefore, qApp is a singleton object which can be reached
as an attribute of Q*Application, but also as a member of the
__builtins__ entries, so you can simply write "qApp" and it will
give you what you expected.

No idea if PyQt wants to go this route, on better avoid this
macro completely. I was just curious how far it goes, but
probably won't write that again :-)

Cheers -- Chris

Christian Tismer-Sperling    :^)   tismer at stackless.com
Software Consulting          :     http://www.stackless.com/
Karl-Liebknecht-Str. 121     :     http://pyside.org
14482 Potsdam                :     GPG key -> 0xE7301150FB7BEE0E
phone +49 173 24 18 776  fax +49 (30) 700143-0023

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 496 bytes
Desc: OpenPGP digital signature
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20180628/c06dab8b/attachment.sig>

More information about the PyQt mailing list