如何在不破坏图像纵横比的情况下调整 QImage 或 QML 图像的大小以适应父容器

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

场景:
我有一个 Image component in QML which contains a QImage 的不同纵横比。

代码:

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
    }
  }
}

问题:
如何设置 my_image_view_containerwidthheight 以便将 my_image 完全放入 my_image_view_container 而不会影响其纵横比?

您可以使用填充模式属性。 像这样

fillMode: Image.PreserveAspectFit