Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting QML Image display size

Tags:

qt

qml

qtquick2

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:
Two images side-by-side, taking up 1/3 of the window height

Actual Appearance:
Two images side-by-side, far larger than their desired size

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' }
}
like image 852
Phrogz Avatar asked Aug 17 '16 01:08

Phrogz


1 Answers

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.
like image 68
Mitch Avatar answered Sep 18 '22 14:09

Mitch