2
votes

I am using QGraphicsView/QGraphicsScene to display an image. The image is always displayed to its original size with scroll bars at the ends. I want QGraphicsView to fit the image automatically as per the the size of the window keeping aspect ratio. I tried this but nothing happened:

ui->graphicsView->fitInView(0,0,ui->graphicsView->width(),ui->graphicsView->height(),Qt::KeepAspectRatio);
1
Where do you call this method? (In constructor some geometry data are not valid.) Qt Documentation suggests to use it in resizeEvent. Does it work if you call it with constants? (fitInView(0,0, 100, 100, Qt::KeepAspectRatio);)sgibb
Yes i call it in constructor (atleast it should work once), i tried constant values also but no effectadnan kamili

1 Answers

15
votes

You are providing the rectangle of the view and not that of the scene.

This should work:

ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);

itemsBoundingRect calculates and returns the bounding rect of all items on the scene. So the graphicsview's view matrix will be scaled in order to fit the contents of the scene.

I would advise you to reimplement resizeEvent and have this call there as well.