[Qt-interest] deleteLater() for QGraphicsItem
Daniel Price
daniel.price at fxhome.com
Fri Dec 4 10:58:14 CET 2009
You are most welcome :)
> -----Original Message-----
> From: Andreas Unger [mailto:andi.unger05 at gmail.com]
> Sent: 03 December 2009 20:22
> To: Daniel Price
> Cc: qt-interest at trolltech.com
> Subject: Re: [Qt-interest] deleteLater() for QGraphicsItem
>
>
>
> 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
>
>
> No virus found in this incoming message.
> Checked by AVG - www.avg.com
> Version: 9.0.709 / Virus Database: 270.14.91/2542 - Release Date:
> 12/03/09 07:32:00
This email is confidential. It may also be privileged or otherwise protected by work product immunity or other legal rules. If you are not the intended recipient please notify the sender. Please delete the message from all places in your computer where it is stored. You should not copy the email or use it for any purpose or disclose its contents to any other person.To do so may be unlawful. Email is an informal means of communicating and may be subject to data corruption accidentally or deliberately. For this reason it is inappropriate to rely on advice contained in an email without obtaining written confirmation of it first.
FXhome Limited is a limited company registered in England and Wales. Registered number: 04172812. Registered office: The Henderson Business Centre, Ivy Road, Norwich, Norfolk, NR5 8BF, U.K.
More information about the Qt-interest-old
mailing list