The motivating scenario: I'm working on a Qt/QWidgets C++ app whose GUI is largely arranged into tabs, via a hierarchy of QTabWidgets. Many of these tabs are various agglomerations of the same content, (e.g. there's a tab with widget A and B, a tab with widget B and C, and so on).
I have one particular widget class W which is a fairly heavyweight GUI object and it appears in many (but not all) of the tabs. Currently I handle that by simply creating a separate object of the W class for each tab I want it to appear in, and that basically works, but it's not 100% satisfactory for a couple of reasons:
- Since the widget is heavy, creating a number of instances of it slows down the GUI's creation on startup, and uses more system resources than I would like.
- Every time the user changes the layout/state of the widget in one tab, I have to manually echo that change to all of its "clones" in the other tabs; otherwise the user will notice the different states of the different W widgets as he moves back and forth from one tab to another. This is doable, but it's a maintenance and testing headache.
So what I'd like to do is create just a single instance of W and have it magically appear in its expected location within whichever tab is currently visible. Since only one tab with W should ever be visible at one time, it seems like a single W instance ought to be enough to accomplish that.
I thought about making a lightweight proxy/container-widget of some sort, and overriding its showEvent() method to setParent() the real W object to be its child as necessary; I think that might work, or it might turn out to be full of gotchas, so I thought I'd ask first if anyone else knows of a more elegant or better-supported way to accomplish the same result.
With a little help I was able to make this technique work, as shown in the example code below. Note that the green label "Shared Widget!" is only created once, but it appears in all 5 tabs (along with various normal QLabels):