How to receive notifications from QGraphicsScene by addItem or itemChange?

In my project, I use QGraphicsScene and add / remove items throughout the code.

Now I want to receive notifications when a QGraphicsItem added or removed. Many Qt classes have notification signals, or at least virtual functions, called upon such changes. I try to avoid adding many lines of code in many places, which is not only cumbersome, but also unsafe (forgetting about inserting / deleting now or in the future).

I need a solution that works with any QGraphicsItem .

This is a list of things that don't work:

  • connect to the QGraphicsScene signal (as in QAbstractItemModel::rowsInserted() ) -> no.
  • inherit from QGraphicsScene and overload the virtual notifier function (as in QTabWidget::tabInserted() ) -> no.
  • Inheriting and overloading addItem() , sending notifications itself (as in QMdiArea::addSubWindow() ) β†’ addItem not virtual and is called from the QGraphicsItems constructors.
  • set event filters to newly added QGraphicsItems β†’ I don’t know how to get a newly added element And it will be a sceneEventFilter , which can only be set on another QGraphicsItems .
  • connect to itemChange() from QGraphicsItem β†’ itemChange not a signal And overloading QGraphicsItem not an option.
  • wrap QGraphicsScene (having the scene as a private member) and only expose the addItem and removeItem β†’ functions, but QGraphicsItems in this scene can still be accessed through the scene() function, so this solution is not safe enough.

How can I be notified of item changes?

If there is a simple way that I just skipped, write to me. Otherwise, I would be very grateful for the ideas.

+8
qt signals notifications qgraphicsscene qgraphicsitem
source share
1 answer

I think that best of all, you can connect to the QGraphicsScene::changed() signal.

It will not tell you which items have been changed / added / deleted since it is designed for QGraphicsView to update the display. But you should be able to find out using the provided areas.

0
source share

All Articles