如何向AppListView的section分隔器传递两个模型角色参数
可行实现方案(共3种,可根据你的实际场景选择)
方案1:直接从模型取对应section的颜色属性(不需要修改现有模型结构,最常用)
因为同一个section下所有条目对应的separatorColorRole和separatorTextRole是固定配对的,直接取当前section第一个条目的颜色属性即可,修改后代码如下:
AppListView { id: list section { property: "separatorTextRole" criteria: ViewSection.FullString delegate: CustomSeparatorDelegate { // 从当前section对应的第一条数据取颜色角色 itemColor: list.model.get(section.index).separatorColorRole itemText: section } } delegate: CustomListDelegate { text: nameRole row: rowRole value: valueRole } }
方案2:基于固定配对规则直接映射(不需要访问模型,性能最优)
你提到颜色和文本是固定成对出现的,直接在分隔器委托内根据文本映射对应颜色即可:
AppListView { id: list section { property: "separatorTextRole" criteria: ViewSection.FullString delegate: CustomSeparatorDelegate { itemText: section itemColor: section === "AA" ? "#b3b3b3" : section === "BB" ? "#eeeeee" : "#ffffff" // 配对规则多的话也可以用switch写法 // itemColor: { // switch(section) { // case "AA": return "#b3b3b3" // case "BB": return "#eeeeee" // default: return "#ffffff" // } // } } } delegate: CustomListDelegate { text: nameRole row: rowRole value: valueRole } }
方案3:复合角色作为section分组依据(适合配对规则不固定、可能后续扩展的场景)
在你的模型中新增一个复合角色,将颜色和文本拼接为一个字符串作为分组依据,使用时拆分即可:
- 模型端新增
separatorGroup角色,值格式为颜色值|文本值,比如#b3b3b3|AA - 修改QML代码如下:
AppListView { id: list section { property: "separatorGroup" criteria: ViewSection.FullString delegate: CustomSeparatorDelegate { property var meta: section.split("|") itemColor: meta[0] itemText: meta[1] } } delegate: CustomListDelegate { text: nameRole row: rowRole value: valueRole } }
内容的提问来源于stack exchange,提问作者Tom Sevet
相关产品推荐
相关产品推荐

