Important: Please read the Qt Code of Conduct -

QGraphicsView displaying blank image

  • I'm trying to open images in a MDI. At the moment the sub window expands to the correct size of the image but the image is blank.

    bool MainWindow::openFile(const QString &fileName)
        QMdiSubWindow *subwindow = new QMdiSubWindow();
        QImage image;
        QGraphicsPixmapItem item( QPixmap::fromImage(image));
        QGraphicsScene *gscene = new QGraphicsScene;
        QGraphicsView view(gscene);
        QGraphicsView *pView = &view;
        return true;

  • Moderators

    @tomasantunes Probably one or all of the stack allocated object are deleted after they go out of the scope i.e after the function ends.

  • Hold on here.... doesn't the QGraphicsScene and QGraphics view have some kind of default point of origin. You may have to set the sizes of both of those objects before doing addItem(). But, this doesn't explain the resizing of the view. Also, I never drop a scene into the constructor of a view. It just has a bad stack thing. I would use view.setScene(gscene) or something along those lines, and set the scene at the bottom of your stack.

    Hope this helps.

  • I think it's about the scope because the image appears correctly if I pop a message box in the same function. Got any suggestion for how to structure this better?

    EDIT: I solved it after following this tutorial:

  • Object which you create on the stack are destroyed when you leave the scope where you declared them. Holding and using a pointer to them will (at best) achieve nothing, or (at worst) cause a crash.

    Create all Object deriving from QObject and QGraphicsItem using new, like so:
    QGraphicsScene *gscene = new QGraphicsScene(this);
    Consider what the parent should be: The object is destroyed when the parent is destroyed. In this example, it makes sense that the scene is destroyed together with the main window, so using the main window as parent makes sense.
    QGraphicsView view = new QGraphicsView(this);
    Same for items. Except that here the parent will be the scene, or another item.

    (I am aware there may be sensible exceptions to the "use new for QObjects and QGraphicsItems" rule - but it's the best way in >90 % of cases, and it's always one way you can do it)

Log in to reply