我确实赞成@CharlesSALA 的答案(因为它有效!),但我认为我也会根据布局提供替代答案。
AspectItem
负责提供正确的边距以保持宽度,使用implicitWidth
. Layout
负责提供正确的边距以保持高度,使用Layout.maximumHeight
.
这同样适用于 aGridLayout
代替ColumnLayout
& RowLayout
。结果略有不同,因为列必须在所有行中保持对齐,但在这两种情况下,矩形的纵横比都根据需要保留。
AspectItem.qml
import QtQuick 2.11
Item {
id: container
property real aimedRatio: 3/4
property alias color: content.color
implicitWidth: height*container.aimedRatio
implicitHeight: width/container.aimedRatio
Rectangle {
id: content
anchors.horizontalCenter: container.horizontalCenter
height: container.height
implicitWidth: height*container.aimedRatio
}
}
main.qml
import QtQuick 2.11
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.11
ApplicationWindow {
id: window
visible: true
width: 800
height: 800
y: 0
ColumnLayout {
anchors.fill: parent
RowLayout {
width: parent.width
AspectItem {
color: "darkseagreen"
aimedRatio: 1/2
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
AspectItem {
color: "seagreen"
aimedRatio: 2/1
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
AspectItem {
color: "lightseagreen"
aimedRatio: 1/2
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
}
RowLayout {
width: parent.width
AspectItem {
color: "darkcyan"
aimedRatio: 2/1
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
AspectItem {
color: "cyan"
aimedRatio: 1/2
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
AspectItem {
color: "lightcyan"
aimedRatio: 2/1
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
}
RowLayout {
width: parent.width
AspectItem {
color: "darksalmon"
aimedRatio: 1/2
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
AspectItem {
color: "salmon"
aimedRatio: 2/1
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
AspectItem {
color: "lightsalmon"
aimedRatio: 1/2
Layout.fillWidth: true
Layout.fillHeight: true
Layout.maximumHeight: implicitHeight
}
}
}
}
结果
启动时:

拉伸窄:

拉宽:
