Search code examples
c++qtqt5qgraphicsviewqimage

Image doesn't fit graphics view frame


I'm working on program which shows users some picture they select. I would like to fit this picture in QGraphicsView's frame, but the picture appears smaller than the frame.

So here's my code:

image = new QImage(data.absoluteFilePath()); // variable data is defined when calling this method
scn = new QGraphicsScene(this); // object defined in header
ui->graphicsView->setScene(scn);
scn->addPixmap(QPixmap::fromImage(*image));
ui->graphicsView->fitInView(scn->itemsBoundingRect(),Qt::KeepAspectRatio);

Here is some example of what is produced with the code above and what I want to get:

image showing produced and wanted looks

The picture's size is around 40 x 60 px when the frame is 200 x 400 px.

What could be wrong?


Solution

  • 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);
    }