Qt objects, Python objects and shadow objects
What happens when you create a Qt object
from Python? A Qt object is an instance of a C++ class, but in
order to be able to manipulate that object from Python, there
needs to be a Python object, too. The answer is that both are
created: a C++ object that contains the real functionality, and
a Python object that "wraps" the C++ object.
Thus, when you call
QWidget() from Python, three things are
created:
The C++ QWidget instance.
Actually it will be a sipQWidget instance which is a
sub-class of QWidget - it is needed to be a catcher for
QWidget's virtual methods and to expose its protected
methods and enums.
the Python object
shadow/proxy which is a thin wrapper around the C++ instance
and which has a unique Python type.
the Python class instance that
you actually deal with in your script. Its instance
dictionary contains a reference (named
__sipThis__) to the shadow object.
The two Python objects are needed because
the programmer wants a class instance, but a Python class
instance doesn't provide you with the capability of wrapping a
C++ pointer.
In fact, both the Qt library and the PyQt
library can create C++ objects. These are passed between them.
For instance, an object could be created by PyQt and passed to
Qt, or it could be created by Qt and passed to Python. Both Qt
and Python have the concept of deleting things — so there
has to be a method of making sure that C++ instances are deleted
properly. If both try to delete the same instance your program
crashes, if neither do then you get memory leaks. Therefore
there is the concept of ownership: the current owner (PyQt or
Qt) is responsible for deleting the C++ instance. Ownership of
an instance may be transferred between PyQt and C++ during the
life of the instance.
Mostly you won't need to concern yourself
with this problem, since PyQt knows exactly when to transfer
ownership of C++ instances automatically.. Complications arise
if you create QObject derived objects
that ‘own', through the QObject
parent-child mechanism, other objects. (This ownership of
objects by other objects is one of the places where Qt deviates
from the C++ standard practice, where the object that creates
another object should also take care of deleting it.)