Untitled

 avatar
unknown
qml
3 years ago
1.3 kB
37
No Index
GridView {
    id: root

    property real itemWidth
    property real itemHeight

    property real spacingX: 0
    property real spacingY: 0

    readonly property real spacingXPerCell: spacingX * (columns-1) / columns
    readonly property real spacingYPerCell: spacingY * (rows-1) / rows

    readonly property int columns: (width + spacingX) / (itemWidth + spacingX)
    readonly property int rows: Math.max(1, Math.ceil(count / (columns+0.0)))

    cellWidth: itemWidth + spacingXPerCell
    cellHeight: itemHeight + spacingYPerCell


    function offsetX(index) {
        let column = index % columns
        return spacingX / columns * column
    }
    function offsetY(index) {
        let row = (index / columns|0)
        return spacingY / rows * row
    }
}

// Usage
GridViewWrapper {
    id: grid

    anchors.fill: parent

    model: 40
    itemWidth: 150
    itemHeight: 200
    spacingX: 10
    spacingY: 20


    delegate: Rectangle {
        color: index % 2 === 0 ? "blue" : "green"

        width: grid.cellWidth
        height: grid.cellHeight

        Rectangle {
            color: "red"
            width: grid.itemWidth
            height: grid.itemHeight

            x: grid.offsetX(index)
            y: grid.offsetY(index)
        }
    }
}
Editor is loading...