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
foo. I do not always know, how many layers there are between
What's the best way to have a reference to
foo in the lowest layer?
- The easiest way would be to make
fooa singleton since I only ever have one
foowindow 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
footo all my constructors and pass it through them. I'd have a reference to
fooin 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 actually
Bar2, and then continue until I have found
fooas 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 until
- Use signals and slots. This sometimes works, but if I'm already 3 layers below
widget4, I can't connect them without
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
What would be a good approach here?