PDA

View Full Version : How to declare Objects (A bit out of context ...but very Confusing)



salmanmanekia
2nd June 2008, 08:56
Hi..
I am facing some problem in understanding ho wthings work in qt...to be specific i had made a program in qt which worked fine until i was doing all the coding in the main(),but then i needed to implement a class because i was using QGraphicsScene::drawBackground...any ways the confusion i am facing is that ,that i am not sure when to use simple object declaration please see my thread for it...
http://www.qtcentre.org/forum/f-qt-programming-2/t-qpaint-class-and-qgraphicsscene-i-am-stuck--13887.html

and when to make some thing like
for.eg
QWidget *wid = new QWidget ..this also confuses me bcoz some time QWidget is only declared this way.. QWidget wid...
maybe my question is a little out of blue....but your help would be appreciated in clearifying it...thanks

JimDaniel
2nd June 2008, 14:55
This is not a Qt question per se, but a C++ question.

When you declare an object like this:

QWidget wid;

It is created on the stack and only has local scope, in other words when you get to the end of the function that declared it, it is destroyed. But normally for GUI elements, you want them to stick around, so you create them instead on the heap with "new" like this:

QWidget * wid = new QWidget();

Here you've created a new widget on the heap that will stick around until you specifically delete it, your only reference to it being a pointer variable. You use a pointer in this case because its often more efficient to store a pointer to an object instead of storing the object itself.