[PyKDE] subclassing in pyqt

Phil Thompson phil at river-bank.demon.co.uk
Sat Dec 23 12:48:25 GMT 2000

David Berner wrote:
> i found a problem while subclassing pyqt-classes in python.
> e.g.
> >>> class Mylistview(QListView):
> >>>   (...)
> >>>
> >>> class Mylistitem(QListViewItem):
> >>>   def __init__(self, parent, name, myvar):
> >>>     apply(QListViewItem.__init__,(self,parent,name)
> >>>     self.MyVar = myvar
> >>>     (...)
> >>>
> >>> a = Mylistview(parent)
> >>> Mylistitem(a, "first item", 5)
> the problem is, when i call a method of Mylistview which returns an item
> like:
> >>> x = a.selectedItem()
> since type(x) is not Mylistitem but QListViewItem, i can not access MyVar:
> >>> print x.MyVar
> >>> (...) AttributeError: MyVar
> AFAIK there are no type-conversions in python (in C a simple cast would do),
> so i see no way to solve this.

Without seeing the full version of your program, this is a bit of a

Are you keeping Python references to the Mylistitem instances you are
creating? (It looks like you aren't in the above.) If you are not then
the Python object (with your variable) will disappear. If you keep a
reference, then the Python object stays alive to be returned by

Here is a thought...

As I've explained before, the C++ QListViewItem instance doesn't get
deleted when the Python object is deleted because its ownership is
transfered to the Qt code. What if I increased the reference count of
the Python instance when ownership is transfered to Qt? Qt then has
responsibility for deleting the reference count - and therefore the
Python object would stick around even though you weren't holding an
explicit reference in your Python code.

This goes against my previously stated philosophy of not messing with
reference counts under the covers - but I can't think of any new
problems it would create.

Anybody any thoughts on whether or not this would break anything?


More information about the PyQt mailing list