调整窗口宽度时如何布局窗口内容?

时间:2015-01-24 11:31:07

标签: qt qml qt5 qt-quick

  

假设我有一个网格,当我减少时显示4X4(4行和4列)   宽度减半,应布局为2X8。我在谷歌和我搜索   上帝有些想法,它可以通过调用JavaScript来实现   动态变化,但我无法获得窗口大小   重新大小。

    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 /或任何带滚动条的内容中安装内容(Fixed Rectangles)。任何人都可以帮助至少提供一些hinds所以我可以解决这个问题吗?如果您知道有任何其他方法可以实现这一目标,请欣赏吗?

1 个答案:

答案 0 :(得分:2)

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

关键点是动态重新计算必要/可用行和列的数量。然后我们可以利用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"}
            }
        }
    }
}
相关问题