The stack object is not recognized by Qt, but the heap object does

I am having difficulty understanding the problem that I encountered while creating the QT class, but I get the feeling that this might be a common thing. The problem was that it only worked after I used the pointer to the object, but did not work with the object variable itself.

In main (), I instantiate the 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 image (item2) was shown only after I changed the last line so that it was a pointer:

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

Why does the object variable not work? Is it because of some internal QT stuff or am I missing something? I also painted a boardScene background, and I saw the color, so I know that it is still β€œalive”.

+3
1

++ , . boardView , Board , ( boardView ).

, , , . .

, QGraphicsView () QWidget, , , QObject. QObject , boardView , parent, , (, ).

+10

Source: https://habr.com/ru/post/1774022/


All Articles