如何使用QML布局在网格中排列纵横比缩放的项目?

rub*_*nvb 5 layout qt aspect-ratio qml layout-anchor

我有一个具有特定长宽比的矩形和一个具有相反长宽比的矩形。我想将它们安排在自己选择的网格布局中(相反,不必是常规网格:我更喜欢可以随意构建RowLayouts和ColumnLayouts 的解决方案)。

我知道我可以使用Layout.fillHeight和缩放布局中的项目Layout.fillWidth。不幸的是,我找不到合适的方法为定义纵横比Rectangle。我知道QML Image可以(通过其fillMode属性)做到这一点,但我认为没有简单的方法可以很好地做到这一点。

任何帮助或正确方向的指点将不胜感激!

注意,我假设要使用QML Layouts,但是如果有一个仅包含锚点或普通Row/ Column设置的功能解决方案,我将全力以赴!

还请注意,我宁愿将两种类型的面积保持Rectangle相同,就像在实验中看起来那样,这并不是那么简单...

编辑

我的意思是尝试减去等面积约束。矩形会填满宽度,但在高度上会留出空间,因为它们受纵横比和填充宽度的限制。高度应该一样,但是我不能将两者结合起来。

1个

Ans*_*mar 0

您可以使用属性绑定来使用width长宽比来绑定height矩形,如下所示,

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.0

Window {
    id: root
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    property int minWidth: 150
    property int maxWidth: 300
    property int minHeight: 150
    property int maxHeight: 250
    property int rowWidth: root.width/3 //Change accordingly the width of each child item w.r.t. the width of the root.
    Row {
        id: layout
        anchors.fill: parent
        spacing: 6
        Rectangle {
            color: 'red'
            // 4/3 is the aspect ratio of the first Rectangle
            height: (3*width/4)<root.minHeight ? root.minHeight : ( (3*width/4)>root.maxHeight ? root.maxHeight : 3*width/4 )
            width: (root.rowWidth) < root.minWidth ? root.minWidth : ( root.rowWidth > root.maxWidth ? root.maxWidth : root.rowWidth)
            Text {
                anchors.centerIn: parent
                text: parent.width + 'x' + parent.height
            }
        }
        Rectangle {
            color: 'green'
            // 3/4 is the aspect ratio of the second Rectangle
            height: (4*width/3)<root.minHeight ? root.minHeight : ( (4*width/3)>root.maxHeight ? root.maxHeight : 4*width/3 )
            width: (root.rowWidth) < root.minWidth ? root.minWidth : ( root.rowWidth > root.maxWidth ? root.maxWidth : root.rowWidth)
            Text {
                anchors.centerIn: parent
                text: parent.width + 'x' + parent.height
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)