使用中继器填充 GridLayout [英] Populate GridLayout with Repeater
问题描述
我尝试使用 Repeater
将单元格添加到我的 GridLayout
.我的数据存储在一个模型中,每个元素包含两个属性:
I try to add cells to my GridLayout
by using a Repeater
. My data is stored in a model and containing two properties per element:
标题
值
我的目标是获得一个 GridLayout
,其中包含第一个单元格中的 Title
和每行第二个单元格中的 Value
.>
My goal is to get a GridLayout
containing the Title
in first cell and the Value
in the second cell of each row.
GridLayout {
id: someId
columns: 2
rowSpacing: 5
columnSpacing: 5
anchors.margins: 5
anchors.left: parent.left
anchors.right: parent.right
Repeater {
model: myModel
Label {
text: modelData.title
}
TextArea {
text: modelData.value
}
}
}
但是 QML Repeater
只允许一个元素.任何想法如何获得我想要的布局?
But QML Repeater
allows only one element. Any ideas how I could get the layout I want?
+------------+---------------------------------------+
| | |
| title0 | value0 |
| | |
| | |
+------------+---------------------------------------+
| | |
| | |
| title1 | value1 |
| | |
| | |
+------------+---------------------------------------+
| | |
| title2 | value2 |
| | |
| | |
+------------+---------------------------------------+
推荐答案
你可以在一个 GridLayout
中简单地使用两个 Repeater
,如下所示:
You can simply use two Repeater
s within a GridLayout
, as follows:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4
Window {
width: 600; height: 400; visible: true
GridLayout {
id: grid
anchors.fill: parent
columns: 2
rowSpacing: 5
columnSpacing: 5
anchors.margins: 5
// example models
property var titles: [ "title1", "title2", "title3", "title4", "title5" ]
property var values: [ "value1", "value2", "value3", "value4", "value5" ]
Repeater {
model: grid.titles
Label {
Layout.row: index
Layout.column: 0
Layout.fillWidth: true
Layout.fillHeight: true
text: modelData
}
}
Repeater {
model: grid.values
TextArea {
Layout.row: index
Layout.column: 1
Layout.fillWidth: true
Layout.fillHeight: true
text: modelData
}
}
}
}
index
参数是免费提供的,用于存储模型的当前行.
The index
parameter is freely available and store the current row of the model.
通过使用Layout.fillWidth
附加属性,您可以控制单列的width
.
By using the Layout.fillWidth
attached property you can control the width
of the single column.
当然,属于一列的每个单元格与该列的所有其他单元格具有相同的大小,这与使用两个 Column
组件不同.
Of course, each cell that belongs to a column has the same size of all the other cells of that column, unlike what happens using two Column
components.
此解决方案有一些缺点,但如果您的目的主要是打印模型中的纯数据,则它是不错的选择.
This solution has a few drawbacks, but it's good if your purpose is mainly to print plain data from a model.
这篇关于使用中继器填充 GridLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!