QGraphicsTextItem: Distinguish "focusOut" from "scene destroyed"
I have subclassed a QGraphicsTextItem, and use it as a text editor.
The desired behavior is:
- If the user edits the text, then leaves the TextItem (e.g. by clicking into the scene background, or by switching to another window), the entered text should be saved
- If the user edits the text, then directly closes the window containing the TextItem, the entered text should be discarded.
I find it hard to distinguish those two.
I use a QWidget as a window, it contains a QGraphicsView. It is also the parent of the QGraphicsScene.
When I close the window, both a implicitly destroyed, calling the destructor of my QGraphicsTextItem subclass. However, before the destructor is called, a focusOut event arrives. It has the same FocusReason (Qt::ActiveWindowFocusReason) as if the user simply switched to a different window.
I also checked whether the itemChange method yields anything useful help. Nope, it doesn't even get called.
Any suggestions how I could distinguish "switching focus to another window" from "closing own window"?
What you could try is subclassing the QGraphicsScene. The focusOut that causes your trouble does go through the focusOutEvent handler of the QGraphicsScene. You likely get the close event of your window before the focusOutEvent in your graphics scene, so the scene, in theory could be aware of the window currently closing and not deliver the event in that case. It's definitely a hack but it might solve your problem.
I'm sure I could rig something along those lines. My idea was, however, to keep the custom TextItem unaware of it's environment, and prevent potential error when it's used in different contexts. It it was a one-time development that ran only in once certain scene and/or one certain view, the solution would be fine.
I certainly understand that - wouldn't be satisfied with that solution either to be honest :). Is your text item a plain QGraphicsItem or a QGraphicsObject? In the latter case you could post a custom event to trigger the actual saving from within the focusOut event, or simply use a queued signal-slot connection which takes less effort. When the item is about to die the enqueued event will likely not get delivered. This might solve your problem.
The queued event idea is interesting. I'll give it some thought. Thanks!