Terry Martin
Terry Martin

Reputation: 579

How to scale images in QGraphicsScene? (Qt 5.11)

I am having some trouble getting the image in an image previewer correctly scale to the window size. I have a ImgViewer window for previewing images, and want to update the displayed image whenever a new file is chosen by the main window. The images are being updated correctly as new ones are clicked in the main window, but the scaling is not applying. The images always show up way too large for the ImgViewer window.

Here is the code I wrote for the image update function:

void ImgViewer::update_img(QString img_path){
    img_object = new QImage();
    img_object->load(img_path);
    image = QPixmap::fromImage(*img_object);
    QPixmap scaled_img = image.scaled(img_object->size(), Qt::KeepAspectRatio);

    scene = new QGraphicsScene(this);
    scene->addPixmap(scaled_img);
    scene->setSceneRect(scaled_img.rect());

    ui->graphicsView->setScene(scene);
}

Do I need to reset the scene every time the window is resized?

Upvotes: 0

Views: 2909

Answers (1)

Use of your windows size in bellow code :

QPixmap scaled_img = image.scaled(this->width(), this->height(), Qt::KeepAspectRatio);

Instead of :

QPixmap scaled_img = image.scaled(img_object->size(), Qt::KeepAspectRatio);

Use of bellows for different aspect ratio :

enter image description here

Upvotes: 2

Related Questions