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 inQAbstractItemModel::rowsInserted()
) -> there is none. - inherit from
QGraphicsScene
and overload a virtual notifier function (as inQTabWidget::tabInserted()
) -> there is none. - inherit and overload
addItem()
, sending notifications myself (as inQMdiArea::addSubWindow()
) ->addItem
isn't virtual and gets called from the constructors ofQGraphicsItems
. - install event filters on newly added
QGraphicsItems
-> no idea how to get the newly added item AND it would be asceneEventFilter
which can only be installed on otherQGraphicsItems
. - connect to
itemChange()
ofQGraphicsItem
->itemChange
is not a signal AND overloadingQGraphicsItem
is not an option. - wrap
QGraphicsScene
(having the scene as a private member) and only expose functionsaddItem
andremoveItem
-> butQGraphicsItems
in that scene could still access it viascene()
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.
addItem()
function in the wrapper. – KassandrakassarabaQGraphicsItem
as all it's scene changes (including scene addition/removal) run through it'ssceneEvent(QEvent* event)
method - which provides a very clean and tunable solution to your problem. – DeuceaddItem()
function isn't virtual and gets called from the constructors ofQGraphicsItem
s. So this would be not a complete solution. – YoshidaQGraphicsObject
as well (which is also in use), thus duplicating the code. Even worse, in order to send signals fromQGraphicsItem
I'd have to inherit fromQObject
, too, which breaks several inheritance hierarchies in my project. – Yoshidascene()->removeItem(this)
- I'd still not be able to prevent that or at least get notified about it. – Yoshida