QGraphicsItem: Notifying parent of changes to boundingRect



  • Hi!

    I'm working with a QGraphicsScene / QGraphicsItems and is trying to create a container class that draws an outline around a number of child items,

    class MyContainer : public QGraphicsItem
    {
    public:
       QRectF boundingRect() const override
       {
          return m_boundingRect;
       }
       void notifyMoved(MyItem* )
       {
          updateBoundingRect();
       }
       void updateBoundingRect()
       {
    	prepareGeometryChange();
        ... //compute new bounding rect containing all the item's bounding rects
       }
       ...
    private:
       QRectF m_boundingRect;
       ...
    };
    

    and

    class MyItem: public QGraphicsItem
    {
    public:
       MyItem(MyContainer* pContainer) 
          : QGraphicsItem(pContainer), m_pContainer(pContainer) {}
       QVariant itemChange(GraphicsItemChange change, const QVariant & value) override
       {
          //notify container if this item moved
          ...
          m_pContainer->notifyMoved(this);
          ...
       }
       ...
    private:
       MyContainer* m_pContainer;
    };
    

    (Not the exact code but this is how it works in principle)

    This works great as long as the items move. Notifications are sent and the container rect (and graphics) are updated properly. However, I run into problems when I change the bounding rect of a contained item. MyItem does not know when its bounding rect changes. How can I inform it? Is there a standard way to do this? Something like this would be useful:

    QGraphicsItem::ItemBoundingRectHasChanged
    

    I could definitely write my own code that notifies whenever i set the bounding rect, but this would get tedious since MyItem may actually be any kind of subclass to MyItem that handles its bounding rect in its own way. I would like to do it "the Qt way"!

    Any ideas are welcome! :-)

    //Björn W



  • Hi, welcome to the Qt forum! If you need graphics items with signals and slots then don't derive MyItem from QGraphicsItem but from QGraphicsObject instead. The rest should be trivial.



  • @Wieland

    That's a good idea, will do. Still, is there any built-in way to get a notification when the boundingRect changes?



  • @BjornW No, there is no built-in way. Standard graphics items aren't derived from QObject to keep them lightweighted, thus they don't emit any signals.



  • @Wieland I was thinking about

    QVariant QGraphicsItem::itemChange(GraphicsItemChange change, const QVariant & value)
    

    or similar. That does not use the signal/slot system.

    Anyway, gonna change my code to use slots.


Log in to reply