[PyQt] SIP: Retaining python class variables of derived C++ class
Phil Thompson
phil at riverbankcomputing.com
Mon Jan 7 16:47:53 GMT 2019
On 7 Jan 2019, at 4:32 pm, Sandro Mani <manisandro at gmail.com> wrote:
>
> Hi
>
> I have the following scenario:
>
> -----------
>
>
> C++:
>
> class AbstractItem {
> AbstractItem(const QString& id);
> virtual ~AbstractItem();
> };
>
>
> class Pool {
> void addItem(AbstractItem* item /Transfer/);
> AbstractItem* getItem(const QString& id);
> };
>
>
>
>
> Python:
>
> class Item(AbstractItem):
> def __init__(self, id):
> AbstractItem.__init__(self, id)
> self.value = "value"
> def getValue(self):
> return self.value
>
>
> pool = Pool()
> pool.addItem(Item("xyz"))
> # ...
> item = pool.getItem("xyz")
> print(item.getValue()) ### AttributeError: 'Item' object has no attribute 'value'
>
>
> -----------
>
>
> The issue is that, when I pass the Python-deriver Item instance to the pool, lose the reference to it, and then re-retreive it from the pool, the Item instance will have lost class variables set in the Item __init__ function. As I understand, this is expected, because SIP keeps a python part and a c++ part of each object, and the python part is garbage-collected when the variable gets out of scope. Is there a way to make the above logic work?
Use of /Transfer/ should get the behaviour that you want. However you need to make sure you are using the right supertype for any classes that implement any sort of ownership rules. Adding the /Supertype=sip.wrapper/ class annotation to both AbstractItem and Pool classes may help.
Phil
More information about the PyQt
mailing list