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?
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.
Use the QImage::scaled function. QImage img("someimage. png"); QImage img2 = img. scaled(100, 100, Qt::KeepAspectRatio);
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.
You can use fillMode property. Like this
fillMode: Image.PreserveAspectFit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With