qml 中 listiew 和repeater混合使用的问题

📅 2026/7/31 9:11:05
qml 中 listiew 和repeater混合使用的问题
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.VirtualKeyboard 2.4 Window { id: window visible: true width: 640 height: 480 title: qsTr(Hello World) // 1. 模拟外部传入的表头字段数据 // 实际项目中这个数组可以从 C 后端、网络请求或配置文件动态获取 property var headerFields: [product, category, price, stock, status] // 2. 模拟外部传入的列表数据 ListModel { id: tableModel ListElement { product: 智能手机; category: 电子产品; price: 3999; stock: 150; status: 有货 } ListElement { product: 无线耳机; category: 配件; price: 599; stock: 45; status: 有货 } ListElement { product: 机械键盘; category: 外设; price: 899; stock: 20; status: 低库存 } ListElement { product: 显示器; category: 电子产品; price: 2599; stock: 0; status: 缺货 } } ListView { id: tableView anchors.fill: parent anchors.margins: 10 model: tableModel clip: true spacing: 1 // 3. 动态表头使用 Repeater 根据 headerFields 的长度生成表头 header: Rectangle { width: tableView.width height: 40 color: #34495e Row { width: parent.width height: parent.height spacing: 1 Repeater { model: headerFields Rectangle { // 动态计算每一列的宽度这里简单平均分配 width: tableView.width / headerFields.length height: parent.height color: transparent Text { anchors.centerIn: parent text: modelData // modelData 即为 headerFields 中的字符串 color: white font.bold: true } } } } } // 4. 动态数据行同样使用 Repeater 生成对应数量的单元格 delegate: Rectangle { width: tableView.width height: 40 // 斑马纹效果 color: index % 2 0 ? #f8f9fa : #ffffff border.color: #e9ecef border.width: 1 readonly property int outerIndex: index Row { width: parent.width height: parent.height spacing: 1 Repeater { // 这里的 model 数量必须与表头字段数量一致 model: headerFields.length Rectangle { width: tableView.width / headerFields.length height: parent.height color: transparent Text { anchors.centerIn: parent text: { var fieldName headerFields[index]; return tableView.model.get(outerIndex)[fieldName] } color: #2c3e50 } } } } } } } /* 注意的点: 1 ListView 的delegate 如果有嵌套Repeater 那么在Repeater里面使用index则是Repeater的index 而不是ListView的index.所以需要在外面写一个 readonly property int outerIndex: index 方便在Repeater找到ListView的index 2 每一个ListElement, model.productmodel[product] 3 在ListView里面可以使用model[product] ,但是不能model[1].因为此时的model相当于是一个ListElement了,但是如果是在Repeater 里面调用model,则此时的model 是Repeater的. 4 ListView使用model Repeater里面使用modelData */