problemofficer
problemofficer

Reputation: 435

Stack object doesn't get recognized by Qt but heap object does

I have difficulties understanding a problem I encountered during instantiation of a QT class but I have the feeling that it might be general oop thing. The problem was that it only worked after I used a pointer to the object but didn't work with just the object variable itself.

In main() I create an instance of a widget:

Board board;
board.show();

Board.h:

class Board : public QWidget
{

    Q_OBJECT

public:
    Board(QWidget* parent = 0);
    virtual ~Board();
};

Board.cpp

Board::Board(QWidget* parent) :
    QWidget(parent)
{

    QGraphicsScene* boardScene = new QGraphicsScene(this);
    boardScene->setSceneRect(this->rect());

    QGraphicsItem* item2 = new QGraphicsPixmapItem(QPixmap("test.jpg"));
    item2->setPos(100,100);
    boardScene->addItem(item2);


    QGraphicsView boardView (boardScene, this);

Now the problem was in the last line. The test picture (item2) was only shown after I changed the last line so that it was a pointer:

QGraphicsView* boardView = new QGraphicsView (boardScene, this);

Why doesn't the object variable work? Is this due to some internal QT thing or am I missing something? I also painted the background of boardScene and I saw the color, so I know it was still "alive".

Upvotes: 3

Views: 199

Answers (1)

In silico
In silico

Reputation: 52197

Because in C++, stack variables are automatically destructed when they go out of scope. In your case, boardView will be destructed when the Board constructor returns, so the test picture doesn't show at all (since boardView doesn't exist anymore).

On the other hand, the lifetime of heap-allocated objects are not bound to the scope they were created in, so it stays alive even after the constructor returns. That's why the test picture was shown only with your second code snippet.

Note that QGraphicsView (indirectly) inherits from the QWidget class which in turn inherits from the QObject class. Since QObjects form object trees, boardView will be properly destructed when the parent is destroyed as well, so you don't need to worry about destroying it once you're done with it (of course, you still have to worry about destroying the root of the object tree).

Upvotes: 10

Related Questions