Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use QML Layouts to arrange aspect ratio scaled items in a grid?

Tags:

I have rectangles with a certain aspect ratio and rectangles with the inverse aspect ratio. I would like to arrange them in a grid layout of my choosing (doesn't need to be a regular grid, on the contrary: I'd prefer a solution where I can build up RowLayouts and ColumnLayouts at will).

I know I can have scaling items in my Layouts using Layout.fillHeight and Layout.fillWidth. Unfortunately, I can find no way to properly define aspect ratios for my Rectangles. I know QML Image can do it (through its fillMode property) but I see no simple way of doing it nicely.

Any help or pointers in the right direction would be much appreciated!

Note I'm assuming QML Layouts is the way to go, but if there is a functional solution with just anchors or a plain Row/Column setup, I'm all for it!

Also note that I would prefer to keep the area of te two types of Rectangle the same, as it seems while experimenting, this is not so trivial...

EDIT

An attempt of what I mean, minus the equal area constraint. The rectangles fill the width, but leave space in the height because they are constrained by their aspect ratio and the filled width. Same should go for the height, but I'm failing at combining the two.

1

like image 601
rubenvb Avatar asked Jan 02 '17 18:01

rubenvb


1 Answers

I have been struggling for few days on the proper way to do that. I could not found any working exemple so I wrote my own.

This rectangle will always respect its aimedRatio and will keeps its margins. The trick here is to treat to different cases : Either the parents ratio is larger that the aimed one or not. In one case you bind the width to parent and set height according to. In the other case you do it the other way.

Rectangle {
    color  : 'green'

    // INPUTS
    property double  rightMargin    : 20
    property double  bottomMargin   : 20
    property double  leftMargin     : 20
    property double  topMargin      : 20
    property double  aimedRatio     : 3/4

    // SIZING
    property double  availableWidth  : parent.width  - rightMargin  - leftMargin
    property double  availableHeight : parent.height - bottomMargin - topMargin

    property bool    parentIsLarge   : parentRatio > aimedRatio

    property double  parentRatio     : availableHeight / availableWidth

    height : parentIsLarge ? width * aimedRatio :  availableHeight
    width  : parentIsLarge ? availableWidth     :  height / aimedRatio

    anchors.top        : parent.top
    anchors.topMargin  : topMargin
    anchors.left       : parent.left
    anchors.leftMargin : leftMargin
}

Hope it will help out people who arrive here with google search !

like image 109
CharlesSALA Avatar answered Sep 24 '22 11:09

CharlesSALA