MemoryManagement of QGraphicsItems



  • Hello,

    I have implemented some "ScreenManagers", they are managing the QGraphicsItems that are in a QGraphicsScene. The Problem is, that it dont know if i should delete the QGraphicsItems from each ScreenManagers. Some of those Items are currently in the scene, that would not be a problem, because the items destructor deletes itself out of the scene. Some of them are not in the scene: This is also not a problem, because i can just delete them. But here is a problem: What about those items that were deleted by the scene? Per example through deleting the scene, or using the scenes user events to delete items... I would then end with a pointer to a QGraphicsItem in my Screenmanager, that is not valid anymore... Normally QT is fixing that by using a QPointer to the items. So all pointers to that item are set to NULL. But for what ever reason it is not possible to put a QGraphicsItem into a QPointer. Why not? And what is the best solution for this problem?

    thanks in advance
    Matthias Thurau



  • QPointer (or rather: QWeakPointer) does not work in this case because QGraphicsItems are not QObjects. They were designed to be as lightweight as possible.

    You can use smart pointer classes if you consistently use QGraphicsObject instead of QGraphicsItem, which however precludes the usage of several standards QGraphicsItems, like QGraphicsPixmapItem.

    But one question you should ask yourself is: Do you have a clear idea who is supposed to control the lifetime of your objects? Having multiple pointers to the same object in different places is always tricky. What is the purpose of your ScreenManager? Does it really need to hold pointers to GraphicsItems that are currently "owned" by a scene? Wouldn't it be enough to hold the pointer to the QGraphicsScene? (which is a QObject, btw., so you can use the smart pointers there)



  • Why not keep the "free" items inside some container, the scene manages the items that are in it, you manage the container that holds the free items, shift items back and forth and so on...


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.