I'm creating a multi window gui program, in c++ with Qt Widgets. I do have many custom gui elements, which usually are c++ classes inherited from QWidget
or other Qt elements. When foo
is the main window, it often looks like this:
Foo = new Foo();
Bar1 *widget1(foo);
Bar2 *widget2(widget1);
Bar3 *widget3(widget2);
Bar4 *widget4(widget3);
foo->addWidget(widget1);
widget1->addWidget(widget2);
widget2->addWidget(widget3);
widget3->addWidget(widget4);
Actually I use std::shared_ptr
everywhere but I'm omitting that here for the sake of readability. Also this is simplified, the order is not always like this and there may be other Qt elements in between.
The argument in the constructors is the "parent" Window. Qt handles the deletion of all my Widgets using the parent structures.
My problem is, that sometimes, I need to access elements of my main window foo
from some Bar
widget down the road. E.g.: "If this is clicked, add another tab to the QTabwidget
in foo
. I do not always know, how many layers there are between foo
and widgetX
.
What's the best way to have a reference to foo
in the lowest layer?
- The easiest way would be to make
foo
a singleton since I only ever have onefoo
window and once it get's closed, my program terminates anyway. But making the whole class static comes with it's own drawbacks. - Add a reference to
foo
to all my constructors and pass it through them. I'd have a reference tofoo
in many places where I do not need one. - I can access the parent reference that got passed through the constructors, but it's a pointer to
QWidget
. I'd have to cast it, check whether it's actuallyFoo
and notBar2
, and then continue until I have foundFoo
. - Set
foo
as a parent for everything, even if it is not really the parent (e.g. in a new Window). This would keep all my elements in memory untilfoo
is destroyed. - Use signals and slots. This sometimes works, but if I'm already 3 layers below
foo
when creatingwidget4
, I can't connect them withoutfoo
.
Currently I have a mixed mess where I sometimes pass a reference to foo
, have some static elements in foo
and at some point cast the parent widget to foo
.
What would be a good approach here?