Qt QML。如何拉伸所有父空间的栅格
我有一个自定义按钮:Qt QML。如何拉伸所有父空间的栅格,qt,qml,qtquick2,Qt,Qml,Qtquick2,我有一个自定义按钮: 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.centerI
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
}
}
它有一个父矩形
:
Rectangle {
width: 500
height: 500
Grid {
anchors.centerIn: parent
rows: 3; columns: 3; spacing: 0
Repeater {
model: 9
Xobtn { }
}
}
}
我需要拉伸
网格中的所有按钮,以获得父矩形中的所有可用空间。我该怎么做?谢谢。网格
只需根据项目大小在其中定位项目即可。要主动调整项目的大小,您需要使用,并告诉它应该如何调整项目的大小。因此,您的代码变成如下所示,注释显示对代码的更改:
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
}
}
}
}
如果您出于某种原因不想依赖于QtQuick.Layouts
,那么您必须自己计算宽度和高度,但如果您不需要统一的网格,这相当麻烦,例如:
Xobtn {
height: grid.parent.height / grid.columns - grid.spacing
width: grid.parent.width / grid.rows - grid.spacing
}
其中,grid
将是网格的id。如果不使用QtQuick.Layouts,您可以执行类似操作(但您需要知道放入网格中的项目的大小:
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
}
}
}
}
}