faspowa
faspowa

Reputation: 61

How tocreate grid on button clicked?

What I want to do is to read dimensions of grid from TextArea elements, and then create this Grid when i click the button. Static version of what i want looks like this:

Grid {
    id: grid
    rows: 8 //i want this to be dynamic value
    columns: 8 //i want this to be dynamic value
    Repeater {
        id: rep
        model: rows * columns
        Rectangle {    // grid will be filled with instances of my qml element
            width:10
            height:10
        }
    }
}

Can you give me any advice on how to do it? Thank you.

Upvotes: 0

Views: 158

Answers (1)

folibis
folibis

Reputation: 12874

Here is an example of the dynamically created Grid:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Dynamic creation example")

    Component {
        id: gridComponent
        Grid {
            id: grid
            rows: 0
            columns: 0
            Repeater {
                model: grid.rows * grid.columns
                Rectangle {
                    width: 400 / grid.columns
                    height: 400 / grid.rows
                    color: Qt.rgba(Math.random(),Math.random(),Math.random(), 1)
                }
            }
        }
    }

    Row {
        spacing: 5
        Text {
            text: "rows: "
        }

        TextInput {
            id: rowInput
            text: "10"
            width: 50
            validator: IntValidator { bottom: 1; top: 100; }
        }

        Text {
            text: "columns: "
        }

        TextInput {
            id: colInput
            text: "10"
            width: 50
            validator: IntValidator { bottom: 1; top: 100; }
        }

        Button {
            text: "Create Grid"
            onClicked: {
                var obj = gridComponent.createObject(container);
                obj.rows = parseInt(rowInput.text);
                obj.columns = parseInt(colInput.text);
                // the same option
                // var obj = gridComponent.createObject(container, {"rows" : parseInt(rowInput.text), "columns" : parseInt(colInput.text)});
            }
        }
    }

    Rectangle {
        id: container
        width: 400
        height: 400
        anchors.centerIn: parent
        border.color: "#999"
        border.width: 1
    }
}

Upvotes: 1

Related Questions