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”.
Because in C++, stack variables are automatically destructed when they go out of scope. In your case,
boardViewwill be destructed when theBoardconstructor returns, so the test picture doesn’t show at all (sinceboardViewdoesn’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 theQWidgetclass which in turn inherits from theQObjectclass. SinceQObjects form object trees,boardViewwill be properly destructed when theparentis 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).