Mohammad Saifullah
Mohammad Saifullah

Reputation: 1143

Qt: issue with QGraphicscene to show an imge

I am trying to develop very simple image viewer using QT. I am using the following code to show the image on QGraphicsScene widget:

QImage image(fileName);


firstPicture = new QGraphicsScene();
firstPicture->addPixmap(QPixmap::fromImage(image));


ui->graphicsView->setScene(firstPicture);
ui->graphicsView->fitInView(firstPicture->sceneRect() ,Qt::KeepAspectRatio);

I am getting the following output: output

How can I fit the image into the GraphicsScene?

Upvotes: 1

Views: 64

Answers (2)

Nejat
Nejat

Reputation: 32645

You can make your custom class which inherits from QGraphicsView. You should reimplement resizeEvent( QResizeEvent *event ) in your custom QGraphicsView like:

void MyView::resizeEvent(QResizeEvent *event)
{

    fitInView(firstPicture->sceneRect(), Qt::KeepAspectRatio);

    QGraphicsView::resizeEvent(event);
}

This way the view will always display the whole scene. I.e. if the window size is changed and the graphicsView is resized, The scene gets scaled and you can see everything appropriately.

Upvotes: 1

Jablonski
Jablonski

Reputation: 18504

This approach works only when view showed your scene. In your case you did not call show(). Solution:

Use your approach when scene already shown.

You can reimplement showEvent and use your approach here.

You can scale image by yourself and set this scaled image to scene.

Also you can try to use: Qt::IgnoreAspectRatio instead of Qt::KeepAspectRatio.

Upvotes: 2

Related Questions