Search code examples
c++qtqgraphicsview

Code works in main but not in other classes


I'm trying to use QGraphicsView and QGraphicsScene in my Qt application but for some reason I can't get it to work. I have the following code which will work if I execute it from the main class but not from a controller class which inherits QObject:

 QGraphicsScene scene;
 scene.setSceneRect(0,0,200,200);
 scene.setBackgroundBrush(Qt::blue);
 QGraphicsView *view = new QGraphicsView();
 view->setScene(&scene);
 view->show();

If I do it in main the scene is blue but if I do it in the other class the scene is white. What is going on?


Solution

  • Change to this:

    {
    QGraphicsScene * scene = new QGraphicsScene();//note that we allocate it on the heap
    scene->setSceneRect(0,0,200,200);
    scene->setBackgroundBrush(Qt::blue);
    QGraphicsView *view = new QGraphicsView();
    view->setScene(scene);
    view->show();
    <...>
    }//your function ends here
    

    In your version, the scene is created on the stack, so if you put this code anywhere in the class, the scene will die immediately at the end of the function. That's why it is white. If you allocate it on the heap, it will stay alive after the closing bracket, and you will be able to see it.

    Please do not forget to delete it after!