[PyKDE] embedding python widgets in C++ app

David Boddie david at boddie.org.uk
Tue Jan 16 00:51:47 GMT 2007


On Monday 15 January 2007 07:51:28 -0800, Patrick Stinson wrote:

> I know I've seen info here and there about using python widgets in C++
> apps, but I need a recap.

I've seen it done so many times I think I need a recap, too!

> So I've already got this great C++ app with an embedded interpreter for
> scripting special app functions. What do I need to do to write a widget in
> python and use it as a child in my C++ app?

It partly depends on how you want to access the widget from C++. Will you
have a C++ factory function that creates and returns Python widgets, or are
you thinking of using a plugin system on the Python side which works like
the one used by Qt Designer?

You need to initialize the interpreter from within your application, import
the Python code as a module or read in the source code from somewhere,
instantiate the widget, then pass back a pointer to its underlying C++
instance. You need to ensure that the Python widget is appropriately
reference counted and that it's ownership is correct - I'm never sure who
should own a widget that you pass back into C++ like this. :-(
Maybe it should be transferred to Qt and its reference count incremented
before it is passed back. It's nearly 2am again, so I may well be confused.

The way I've tried to avoid this is to use factory functions provided by
existing classes in Qt, subclassing those classes in Python, and maintaining
a reference to an instance of each factory for the lifetime of the
application. This way, I can try to minimize the effects of my carelessness
with regard to lost references and non-garbage-collected Python objects.

Jim and I worked on some code to do this for KDE 3, but I think there's a
much better chance to make something that's more widely usable with PyQt4,
and perhaps we can try to re-use what we learned when KDE 4 appears.

David




More information about the PyQt mailing list