调整 window 宽度时如何布局 Window 的内容?

How to Layout Contents of Window when Resizing window width?

Suppose I have a Grid, shows 4X4(4 rows and 4 columns), when I reduce the width by half, It should layout as 2X8. I search in Google, and I god some idea that, it can be achieve through calls of JavaScript to change dynamically, but I have unable to get the window size after re-size.

    import QtQuick 2.2

    Grid{
        id:root
        property int rootWidth:400//Created type to change using javascript
        property int rootHeight:400//Created type to change using javascript
        width:rootWidth
        height:rootHeight

        property int myRows: 4//Initially 4X4
        property int myColumns: 4
        rows: myRows
        columns: myColumns
        onWidthChanged:{ widthChange()}//Executed javascript, when width changes.
        Repeater{
            model:16
            //Fixed Rectangle.
            Rectangle{radius:36;width:100;height:100;color:"blue"}

        }
        function widthChange(){
            //It seems, this condition failes, How to get the width of the
            //window, after resizing the window?
            if( root.width > 200 & root.width <400 )
            {
            //When width is less than 400 and greater than 200, set Grid as 2X4.
            root.myColumns = 2;
            root.myRows = 8;
            root.rootWidth=200;
                root.rootHeight= 800;
            }
        }
    }

我想要实现的是,我需要根据设备宽度将内容(固定矩形)放入 Grid/or 任何带有滚动条的内容。 可以任何人都至少提供一些帮助所以我可以解决这个问题吗?如果您知道任何其他方法来实现这一目标,我将不胜感激?

根据问题,我假设您还需要 ScrollBar,因此我添加了 ScrollView。即使我们去掉后者,一般的方法仍然适用。

关键在于动态重新计算necessary/available行数和列数。然后我们可以利用 QML 绑定并直接将表达式设置为 rowscolumns 属性,这样当大小改变时,值也会相应改变。生成的代码在下面的示例中用 1)2).

突出显示
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Window 2.2

Window{
    id: root
    width: 300
    height: 300
    visible:  true

    ScrollView {
        id: scroller
        width: parent.width
        height: parent.height
        Grid{
            // 1) calculate enough columns to fill the width
            columns: Math.floor(scroller.width / 100)  
            // 2) calculate required rows to contain all the elements
            rows: Math.ceil(model.count / columns)  

            Repeater{
                id: model
                model:16
                Rectangle{radius:36;width:100;height:100;color:"blue"}
            }
        }
    }
}