Qt5 C++ QGraphicsView: Images don't fit view frame

Solution for my question is showEvent() for Dialog. This means that you can't call fitInView() before the form is showed, so you have to create showEvent() for dialog and the picture will be fitted into QGraphics View's frame.

And example code which you have to add into dialog's code:

void YourClass::showEvent(QShowEvent *) {
    ui->graphicsView->fitInView(scn->sceneRect(),Qt::KeepAspectRatio);
}

The reason you're not seeing your image as you want it is because the QGraphicsView function fitInView does not do what you think it does.

It ensures that the object fits inside the viewport, without any overlap of the borders of the view, so if your object was not in the view, calling fitInView will cause the view to move / scale etc to ensure that the object is completely visible. Also, if the viewport is too small for the area provided to fitInView, nothing will happen.

So, to get what you want, map the extents of the GraphicsView coordinates to the GraphicsScene and then set the image's scene coordinates to those. As @VBB said, if you stretch the image, it may change the aspect raio, so you can use scaledToWidth on the QPixmap.

Something like this: -

QRectF sceneRect = ui->graphicsView->sceneRect(); // the view's scene coords
QPixmap image = QPixmap::fromImage(*image);

// scale the image to the view and maintain aspect ratio
image = image.scaledToWidth(sceneRect.width());

QGraphicsPixmapItem* pPixmap = scn->addPixmap(QPixmap::fromImage(*image));

// overloaded function takes the object and we've already handled the aspect ratio
ui->graphicsView->fitInView(pPixmap);

You may find that you don't need the call to fitInView, if your viewport is in the right place and if you don't want it to look pixellated, use an image with a high resolution.