Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notifications from QGraphicsScene on addItem or itemChange?

In my project I'm using a QGraphicsScene and adding / removing items all over the code.

Now I want to get notified whenever a QGraphicsItem gets added or removed. Many Qt classes have notification signals or at least virtual functions that get called on such changes. I'm trying to avoid adding many rows of code in many places which is not only cumbersome but also unsafe (forgetting an insert / removal now or in the future).

I need a solution that works with any QGraphicsItem.

This is a list of things that do not work:

  • connect to a signal of QGraphicsScene (as in QAbstractItemModel::rowsInserted()) -> there is none.
  • inherit from QGraphicsScene and overload a virtual notifier function (as in QTabWidget::tabInserted()) -> there is none.
  • inherit and overload addItem(), sending notifications myself (as in QMdiArea::addSubWindow()) -> addItem isn't virtual and gets called from the constructors of QGraphicsItems.
  • install event filters on newly added QGraphicsItems -> no idea how to get the newly added item AND it would be a sceneEventFilter which can only be installed on other QGraphicsItems.
  • connect to itemChange() of QGraphicsItem -> itemChange is not a signal AND overloading QGraphicsItem is not an option.
  • wrap QGraphicsScene (having the scene as a private member) and only expose functions addItem and removeItem -> but QGraphicsItems in that scene could still access it via scene() function, so this solution is not safe enough.

How can I get notifications on item changes?

If there is an easy way that I simply missed, please point me to it. Else, I'd appreciate ideas on this very much.

like image 609
Martin Hennings Avatar asked Oct 22 '12 11:10

Martin Hennings


1 Answers

I think the best you can do is to connect to QGraphicsScene::changed() signal.

It will not tell you what items are changed/added/removed since it's intended for QGraphicsView to update the display. But you should be able to find out using the supplied regions.

like image 118
Stephen Chu Avatar answered Sep 20 '22 04:09

Stephen Chu