我有一个自定义按钮:
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 { }
}
}
}
我需要拉伸(stretch)Grid
中的所有按钮以获取父矩形
中的所有可用空间。我怎样才能做到这一点?谢谢。
最佳答案
Grid
只是将项目放置在其中,并尊重项目的大小。要主动调整项目大小,您需要使用 GridLayout
,并告诉它如何使用 Layout
attached properties 调整项目大小。 。所以你的代码变成这样,注释显示对你的代码的更改:
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。
关于qt - QML。如何为所有父空间拉伸(stretch)网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30415853/