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

user1257255 picture user1257255 · Jun 10, 2013 · Viewed 14.5k times · Source

I'm working on program which shows user some picture that is selected by him. But there is a problem because I would like to fit this picture in QGraphicsView's frame and the picture is really 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);

I was trying a lot of solutions that I found on web, but no one didn't help me. The picture is in size around 40 x 60 px when the frame is 200 x 400 px. What could be wrong?

Here is some example of what is produced with code above and what I want to get out: enter image description here

Answer

user1257255 picture user1257255 · Jun 13, 2013

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