PDA

View Full Version : Layout parents



qtnewbie500
5th April 2012, 21:49
While trying to understand the difference between creating widgets on the stack or the heap, I came across this behaviour that puzzles me regarding layouts:

int main(int argc, char *argv[]){
QApplication app(argc, argv);
QWidget win;
QVBoxLayout layout(&win);


This will work fine. Then, while trying to invert the order of creation to see what would happen when the objects go out of scope, this happened:

int main(int argc, char *argv[]){

QApplication app(argc, argv);
QVBoxLayout layout;
QWidget win;
layout.setParent(&win);


I was expecting some crash due to win trying to delete the stack created layout, but instead this is what I got:

QLayout::parentWidget: A layout can only have another layout as a parent.

But in the version, isn't the layout being created with the QWidget as parent? I expected a crash when the destructor got called, but not this... can someone explain this to me?

Thank you!
Newbie.

wayfaerer
6th April 2012, 04:07
setParent is a method of QObject, so I don't really think it provides the functionality you were aiming for. I believe setParent is used more to keep track of the memory used by the object. My guess is that the error message is just clunky.

AFAIK you are never supposed to create GUI objects on the stack, but I could be wrong.