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

Kyle Altendorf sda at fstab.net
Thu Jun 28 13:52:56 BST 2018


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).

https://github.com/qt/qtbase/blob/a37dd93defd91b79fb6730d0ff0515a66a0d3972/src/widgets/kernel/qapplication.h#L70

     #define qApp (static_cast<QApplication 
*>(QCoreApplication::instance()))

Cheers,
-kyle


More information about the PyQt mailing list