[solved]Why can't declare an object layout management, must be a pointer?



  • when we use the layout to manage some buttons ,such as:

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(btnfirst);
    layout->addWidget(btnsecond);
    layout->addWidget(btnthree);
    layout->addWidget(btnself);
    layout->addWidget(btnexit);
    QWidget *p = new QWidget;
    p->setLayout(layout);'''
    

    that is right,but the following is wrong ,why?

    QVBoxLayout layout;
    layout.addWidget(btnfirst);
    layout.addWidget(btnsecond);
    layout.addWidget(btnthree);
    layout.addWidget(btnself);
    layout.addWidget(btnexit);
    QWidget *p = new QWidget;
    p->setLayout(&layout);
    

    I don't know why , we must be use a pointer ? (thank you!)



  • Hi and welcome to devnet,

    each QObject instance has an array of pointers of its children; it uses that list to manage memory (destroys the children in the destructor) and visibility (hides the children when is hidden, resizes them according to layouts, ....).

    Your code doesn't work because at the end of the function, the layout variable goes out of scope and is destroyed; so the pointer you passed to setLayout becomes invalid.



  • @mcosta thank you very much! I get it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.