QML. How to stretch the grid to the entire parent space
I have a custom button:
import QtQuick 2.0
Rectangle {
id: xobutton
width: 100
height: 100
property string label: "?"
border.width: 2
Text {
id: xobuttonLabel
text: label
font.pointSize: 75
anchors.centerIn: parent
}
}
It has a parent Rectangle
:
Rectangle {
width: 500
height: 500
Grid {
anchors.centerIn: parent
rows: 3; columns: 3; spacing: 0
Repeater {
model: 9
Xobtn { }
}
}
}
I need to stretch all buttons in Grid
for all free space in the parent Rectangle
. How can i do this? Thank.
source to share
Grid
simply positions the elements in it, respecting the size of the elements. In order for the elements to be actively modified, you need to use GridLayout
and tell it how the elements should be modified using Layout
attached properties . So your code will become something like this, comments showing your code changes:
import QtQuick.Layouts 1.1 // needed for GridLayout
Rectangle {
width: 500
height: 500
GridLayout {
anchors.fill: parent // GridLayout must have the right size now
rows: 3; columns: 3
columnSpacing: 0; rowSpacing: 0 // changed from spacing: 0
Repeater {
model: 9
Xobtn {
// attached properties guiding resizing
Layout.fillHeight: true
Layout.fillWidth: true
}
}
}
}
If you don't want to depend on for some reason QtQuick.Layouts
, you have to calculate width
it height
yourself, but this is rather awkward if you need something other than a single grid, something like:
Xobtn {
height: grid.parent.height / grid.columns - grid.spacing
width: grid.parent.width / grid.rows - grid.spacing
}
where Grid
will be the grid id.
source to share
Without using QtQuick.Layouts, which are a little more expensive, you can just do something like this (but you need to know the size of the items you are placing on the grid:
import QtQuick 2.0
Rectangle {
id: root
width: 500
height: 500
readonly property int rectSize: 100
Grid {
anchors.centerIn: parent
rows: 3; columns: 3;
columnSpacing: (parent.width - (root.rectSize * columns)) / (columns - 1)
rowSpacing: (parent.height - (root.rectSize * rows)) / (rows - 1)
Repeater {
model: parent.rows * parent.columns
Rectangle {
id: xobutton
width: root.rectSize
height: root.rectSize
property string label: "?"
border.width: 2
Text {
id: xobuttonLabel
text: label
font.pointSize: 75
anchors.centerIn: parent
}
}
}
}
}
source to share