Solved setCentralWidget() and automatic deletion
-
I'm a newbie at Qt and I'm building my first app.
In order to make things more modular, I created three QWidgets that reflect the three very different states of the app. A QMainWindow-derived class is responsible to "load and unload" those widgets through setCentralWidget(), managing transition from one to another.
However, I found out that, when you put a QWidget inside something (in my case set it as the central widget of the MainWindow), that "something" acquires ownership of the QWidget and is responsible for its deletion. My problem is that I want to preserve the state of those QWidgets between transitions, so I can't allow them to be deleted.Is there any elegant solution to this? I tried to find out how are those pointers stored in the parent widget in order to check if it's possible to force the framework to preserve QWidgets through the use of shared pointers, but wasn't able to.
-
@Ignis
Before you spend any more time on"load and unload" those widgets through setCentralWidget(), managing transition from one to another.
have you seen https://doc.qt.io/qt-5/qstackedwidget.html, which is commonly used for what sounds like your usage?
-
@Ignis
Before you spend any more time on"load and unload" those widgets through setCentralWidget(), managing transition from one to another.
have you seen https://doc.qt.io/qt-5/qstackedwidget.html, which is commonly used for what sounds like your usage?
-
@Ignis said in setCentralWidget() and automatic deletion:
Is there any elegant solution to this?
Yes. Put a stack widget (
QStackedWidget
) as your central widget and add your widgets to it. Then you can manually switch between them. If you want to take the widget out of the stack (as it takes ownership by default too), you can useQStackedWidget::removeWidget
. -
@JonB Thanks, I actually used QStackedWidget inside those QWidget but didn't think about it in this case.