【发布时间】:2020-05-27 20:48:34
【问题描述】:
我想要在 GridLayout 中显示以下 JSON。
此 JSON 在 QML 文件中接收并分配给属性。
{
{
"id":1
"name": "abc1"
"age": 10
"city": "xvy"
"gender": "m/f"
},
{
"id":2
"name": "abc2"
"age": 10
"city": "xvy"
"gender": "m/f"
},
{
"id":2
"name": "abc3"
"age": 10
"city": "xvy"
"gender": "m/f"
}
}
我想在 5-Columns 和 3-Rows GridLayout 中显示此 JSON。
如下表所示:
+---------+--------------------+-----------------+-----------------+----------------+
| Id | Name | Age | City | Gender |
+---------+--------------------+-----------------+-----------------+----------------+
| 1 | TextFiled | TextFiled | TextFiled | ComboBox |
+---------+--------------------+-----------------+-----------------+----------------+
| 2 | TextFiled | TextFiled | TextFiled | ComboBox |
+---------+--------------------+-----------------+-----------------+----------------+
| 3 | TextFiled | TextFiled | TextFiled | ComboBox |
+---------+--------------------+-----------------+-----------------+----------------+
到目前为止,我已经想到了以下解决方案:
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: 5
rowSpacing: 2
columnSpacing: 2
anchors.margins: 5
// example models
property var id: [ 1, 2, 3, 4, 5 ]
property var name: [ "value1", "value2", "value3", "value4", "value5" ]
property var age: [ 10, 20, 30, 40, 50 ]
property var city: [ "value1", "value2", "value3", "value4", "value5" ]
property var gender: [ "m", "f", "m", "f", "m" ]
Repeater {
model: grid.id
Label {
Layout.row: index
Layout.column: 0
Layout.fillWidth: true
Layout.fillHeight: true
text: modelData
}
}
Repeater {
model: grid.name
TextFiled {
Layout.row: index
Layout.column: 1
Layout.fillWidth: true
Layout.fillHeight: true
text: modelData
}
}
Repeater {
model: grid.age
TextFiled {
Layout.row: index
Layout.column: 2
Layout.fillWidth: true
Layout.fillHeight: true
text: modelData
}
}
// And rest of Repeater for next columns
// ....
}
}
这是正确的方法吗?
此外,我想将 ComboBox 和 TextFiled 中的更新值从网格保存到 JSON,我该怎么做?
【问题讨论】:
-
我认为您可以通过在两级中继器设置中使用Object.keys() 函数来使显示工作
-
如果你有一个合适的模型,可以使用新的 TableView 和 DelegateChooser 作为代理。
-
@Amfasis:我不太清楚 Object.keys() 是什么,请您详细解释一下。
-
@Mitch:我认为 DelegateChooser 适合这个要求,但现在不确定如何在这种情况下使用它,因为我是 QML 新手。我还想保存用户更新后的输入值。
-
Object.keys() 方法为您提供了一个对象(例如第一个对象)中所有键的列表,您可以将其提供给中继器,这样中继器将为每一列实例化委托你有
标签: qt qml qtquick2 grid-layout qt-quick