Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize a QImage or QML Image to fit parent container without breaking the Image's aspect ratio

Scenario:
I have an Image component in QML which contains a QImage of varied aspect ratios.

Code:

Window {
  id: app_window
  visible: true

  Rectangle {
    id: my_image_view_container
    width: app_window.width
    height: app_window.height

    Image {
       id: my_image
       // changes at runtime based on the image my app selects
       source: "random/path/to/an/image.jpg"
       width: sourceSize.width
       height: sourceSize.height
       scale: Qt.KeepAspectRatio
    }
  }
}

Question:
How do I set the width & height of the my_image_view_container so as to fit my_image completely inside my_image_view_container without disturbing its aspect ratio?

like image 584
TheWaterProgrammer Avatar asked Dec 12 '17 13:12

TheWaterProgrammer


People also ask

How do I make an image fit a Div perfectly?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

How do you scale an image in QT?

Use the QImage::scaled function. QImage img("someimage. png"); QImage img2 = img. scaled(100, 100, Qt::KeepAspectRatio);

How do I fit a large image in HTML?

One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels. For example, the original image is 640×960.


1 Answers

You can use fillMode property. Like this

fillMode: Image.PreserveAspectFit
like image 93
Andrey Semenov Avatar answered Sep 25 '22 00:09

Andrey Semenov