首页 文章

如何使用QML布局在网格中排列宽高比缩放项?

提问于
浏览
3

我有一定宽高比的矩形和具有反长宽比的矩形 . 我想在我选择的网格布局中安排它们(不喜欢我可以随意构建 RowLayoutColumnLayout 的解决方案) .

我知道我可以使用 Layout.fillHeightLayout.fillWidth 在我的布局中使用缩放项目 . 不幸的是,我无法正确定义 Rectangle 的宽高比 . 我知道QML Image 可以做到这一点(通过它的 fillMode 属性),但我认为没有简单的方法可以很好地完成它 .

任何帮助或指示正确的方向将非常感谢!

注意我假设QML布局是要走的路,但是如果有一个功能性解决方案只有锚点或简单的 Row / Column 设置,我就是全力以赴!

另外请注意,我宁愿保持两种类型的 Rectangle 的区域相同,正如实验中所看到的那样,这不是那么微不足道......

EDIT

尝试我的意思,减去相等的面积约束 . 矩形填充宽度,但在高度上留出空间,因为它们受纵横比和填充宽度的约束 . 同样应该是高度,但我没有把两者结合起来 .

1

1 回答

  • 0

    您可以使用属性绑定使用纵横比将矩形的 widthheight 绑定,如下所示,

    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
                }
            }
        }
    }
    

相关问题