[Qt-interest] deleteLater() for QGraphicsItem
Andreas Unger
andi.unger05 at gmail.com
Thu Dec 3 21:21:45 CET 2009
On Thu, Dec 3, 2009 at 4:19 AM, Daniel Price <daniel.price at fxhome.com>wrote:
> We hit the same problem but there is a really simply solution – when you
> remove the item from the scene, wrap the pointer to in a QObject-derived
> class which calls deleteLater() in the constructor. Create this object on
> the heap with new() but ignore the return pointer. In the destructor, delete
> the graphics item. Here’s my templated version that can be used with any
> type:
>
>
>
> #include <QObject>
>
>
>
> template <typename T>
>
> class DelayedDelete : public QObject
>
> {
>
> public:
>
> explicit DelayedDelete(T *&item) : m_item(item)
>
> {
>
> item = 0;
>
> deleteLater();
>
> }
>
> virtual ~DelayedDelete()
>
> {
>
> delete m_item;
>
> }
>
> private:
>
> T *m_item;
>
> };
>
>
>
> You’ll notice that the constructor takes a reference to the original
> pointer which it sets to 0 after copying it in the initialize list – this
> avoid leaving a hanging pointer in the calling code which DelayedDelete has
> taken ownership of. Here’s how it’s called:
>
>
>
> scene->removeItem(gfxItem);
>
> new DelayedDelete<RectItem>(gfxItem); // would have crashed if gfxItem was
> deleted here
>
>
>
> Where RectItem is my QGraphicsItem-derived class. As you can see it’s
> fire-and-forget. Qt will delete the DelayedDelete instance during the next
> event loop. But as far as your code is concerned, gfxItem is dead.
>
Fantastic! This worked for me.
Thanks a lot,
Andreas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20091203/cd2b1671/attachment.html
More information about the Qt-interest-old
mailing list