User Tools

Site Tools


fitting_a_square_inside_a_rectangle_and_maintaining_aspect_ratio

Table of Contents

Square in Rectangle

Run this up in a bare QML project and resize the window.

The margins are given as the constants in the expression.

Unsolved problems/idea.

  • “Math.min” is called a lot. Trying to substitute “width” in the “x” calculations and “height” in the “y” calculations does not work. Probably something to do with ordering.
  • Use an “Item” between the outer and inner rectangle to perform the margin calculations using “anchors.margin” then the inner rectangle only needs to work out centering
import QtQuick 2.10
import QtQuick.Controls 2.2
import QtQuick.Window 2.10
 
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Square in a Rectangle")
    Rectangle {
        color:"#606060"
        anchors.fill: parent
        Item {
            anchors.fill: parent
            anchors.margins: 10
            Rectangle {
                // Math.min(parent.width, parent.height) gives the width AND height of this box
                // wrap this in a further item if you want a margin (see above)
                width: Math.min(parent.width, parent.height)
                height: Math.min(parent.width, parent.height)
                // Either x or y will be 0. The other will be a delta between the min
                // and itself. Half of that is enough to center the object
                x: (parent.width - Math.min(parent.width, parent.height)) / 2
                y: (parent.height - Math.min(parent.width, parent.height)) / 2
                color: '#a0a0a0'
                Button {
                    // this is just here to show you how to put things inside
                    anchors.fill:parent
                    text:'Stretchy Box'
                    font.pixelSize: height * 0.1
                    onClicked: {
                        text = "You\nclicked\nme!"
                    }
                }
            }
        }
    }
}
fitting_a_square_inside_a_rectangle_and_maintaining_aspect_ratio.txt · Last modified: 2018/05/01 19:01 by xylene