PDA

View Full Version : button doesn't show up



Qqt
13th December 2010, 07:46
Hello,

I am practicing the Qt tutorial here
http://doc.qt.nokia.com/4.3/tutorial-t4.html

Note that the QPushButton quit in constructor of MyWidget is a pointer. The example code works fine. But the button doesn't show up in the window after I changed the pointer to a stack variable, like


QPushButton quit(tr("Quit"), this);
quit.setGeometry(62, 40, 75, 30);
quit.setFont(QFont("Times", 18, QFont::Bold));

connect(&quit, SIGNAL(clicked()), qApp, SLOT(quit()));

Can any expert point out why the button is not displayed after the change? Why is pointer important here? Thank you.

hackerNovitiate
13th December 2010, 08:33
Your stack variable is a LOCAL variable in the constructor. Memory for local variables get destroyed when the function ends -- thus the button only exists from Line #1 of your post (when it's created) to the "}" after Line #5 (when it gets destroyed).

To stop the button from getting destroyed, you need to use the "new" keyword to allocate it on the heap instead of on the stack. This way, it continues to exist even after the function ends.


Note that the QPushButton quit in constructor of MyWidget is a pointer
Small technicality: The QPushButton is not a pointer; the QPushButton is an object in the heap, and the pointer tells you the QPushButton's exact location within the heap.

Qqt
13th December 2010, 09:03
thank you.