Adjusting QML Image display size

天大地大妈咪最大 提交于 2019-12-12 10:43:03

问题


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.

Desired Appearance:

Actual Appearance:

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.

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

回答1:


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

with

Layout.preferredWidth: 100
Layout.preferredHeight: 100

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


来源:https://stackoverflow.com/questions/38986928/adjusting-qml-image-display-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!