Please nominate your Qt Champions for 2021!

Reparenting and undo reparenting QWidget

  • Here's the scenario:

    1. I have a given set of data models - let's say they are just integer values.
    2. I have one page - simple QWidget with vertical layout for instance, that contains views to all models - let's say they are just QLabels that print the integer value, and another one that contains views for a subset of those models.
    3. Only one page is visible at a time.

    The question:
    I want to save memory and create one-to-one relationship between models not one-to-many. I want to reparent the views between the pages.

    What could be lost is the layout order.

    Any suggestions how to best employ this technique?

  • Hi there,
    Don't really get want you want to do, but in Qt all pareting is done by the QObject class. When you set the parent of a widget to a different widget, the old parent looses it's child automaticly.
    The problem you encounter is that the layout order is lost? What do you mean by that? If the models them selfs stay in memory and are only set to a different parent, no data should be lost at all, or am I missing something?
    You post is a bit abstract to comment on.

  • "Here":'s what I want to do.

    What is the best way to transfer the widgets parenthood between the pages?
    A solution could be to subclass the QWidget that represents the page and make the page reparent all shared widgets in the show event.

    Or another solution could be to keep track of when the QWidget's parent gets changed:

    class QWidget {
    virtual void changeEvent(QEvent* event)
    if (event->type() == QEvent::ParentChange)

    if (event->type() == QEvent::ParentAboutToChange)


    Probably the best solution is to rework the whole page's layout everytime.

Log in to reply