调整 QML 图像显示大小

问题描述:

我有一个带有嵌套 RowLayout 的 QML 窗口.在内排,我有两张图片.这些图像的源 .png 文件(有意)相当大.当我尝试在这些图像上设置 height 属性以使它们变小时,它们仍然被绘制得很大.

I have a QML window with a nested RowLayout. In the inner row I have two images. The source .png files for these images are (intentionally) rather large. When I attempt to set the height property on these images to make them smaller, they are still drawn large.

期望的外观:

实际外观:

让它们变小的唯一方法是设置 sourceSize.height:100 而不是 height:100;然而,这不是我想要的.我希望它们能够在不重新加载的情况下放大和缩小.

The only way I have been able to get them to be small is to set the sourceSize.height:100 instead of height:100; however, this is not what I want. I want them to be able to scale up and down without reloading.

如何修复我的 QML 以使图像具有其包含的 RowLayout 的高度?

How can I fix my QML so that the images take on the height of their containing RowLayout?

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
  width:600; height:300
  visible:true

  Rectangle {
    color:'red'
    anchors { top:header.bottom; bottom:footer.top; left:parent.left; right:parent.right }
  }

  header:RowLayout {
    id:header
    spacing:0
    height:100; width:parent.width

    RowLayout {
      id:playcontrol
      Layout.minimumWidth:200; Layout.maximumWidth:200; Layout.preferredWidth:200
      height:parent.height
      Image {
        // I really want these to take on the height of their row
        source:'qrc:/img/play.png'
        width:100; height:100
        fillMode:Image.PreserveAspectFit; clip:true
      }
      Image {
        source:'qrc:/img/skip.png'
        width:100; height:100
        fillMode:Image.PreserveAspectFit; clip:true
      }
    }

    Rectangle {
      color:'#80CC00CC'
      Layout.minimumWidth:200
      Layout.preferredWidth:parent.width*0.7
      Layout.fillWidth:true; Layout.fillHeight:true
      height:parent.height
    }
  }

  footer:Rectangle { height:100; color:'blue' }
}

使用布局时,切勿指定项目的widthheight;改用 Layout 附加属性.布局本身将设置 widthheight,有效地覆盖您设置的任何内容.

When using layouts, never specify the width or height of the item; use the Layout attached properties instead. The layout itself will set the width and height, effectively overriding whatever you set.

因此,对于您的图像,请替换

So, for your images, replace

width:100; height:100

Layout.preferredWidth: 100
Layout.preferredHeight: 100

这在此处有记录.具体来说,widthheight 仅用作最终回退",它们的行为不会像您预期的那样.

This is documented here. Specifically, the width and height are only used as a "final fallback", and they won't behave as you'd expect.

您的代码中还有其他地方会发生这种情况:

There are other places in your code where this occurs:

  • playcontrol 设置height: parent.height(填充父级的宽高为布局的默认行为,所以这应该不是必需的.
  • playcontrol 布局中的 Rectangle 也设置了 height: parent.height.
  • playcontrol sets height: parent.height (filling the width and height of the parent is the default behaviour for layouts, so this shouldn't be necessary anyway).
  • The Rectangle within the playcontrol layout also sets height: parent.height.