How QApplication() and QWidget() are connected?
This is an example code that I copied, it creates QApplication object and QWidget object, but there is no link between the two objects. I expected something like app.setWidget(did)
to teach PySide/PyQt controller about the widget that was created.
# http://zetcode.com/gui/pysidetutorial/firstprograms/
# 1. PySide.QtGui is the class
import sys
from PySide import QtGui
# 2. setup the application
app = QtGui.QApplication(sys.argv)
# 3. create the widget and setup
wid = QtGui.QWidget()
wid.resize(250, 150)
wid.setWindowTitle('Simple')
# 4. Show the widget
wid.show()
# 5. execute the app
sys.exit(app.exec_())
What's the magic behind this?
QApplication
is a singleton so it would be pretty easy, forQWidget
to do:QApplication.instance()
and interact with theQApplication
instance.In fact trying to instantiate
QWidget
before theQApplication
leads to an error:Which probably means this is what happens.
Edit: I've downloaded the qt sources and in fact, in
src/gui/kernel/qwidget.cpp
, line 328, there is:Where
qApp
is a pointer to theQApplication
instance(i.e. it is equivalent to callingQApplication.instance()
).So, in the end, the
QWidget
interacts with theQApplication
via a global variable, even though it isn't necessary. They probably useqApp
instead ofQApplication.instance()
to avoid unnecessary overhead that might happen when creating/destroying manyQWidget
s.