QML中Repeater嵌套Delegate出现modelData未定义错误求助
问题排查与解决方案
问题原因
你在ListModel中存入的selectionColors数组会被Qt转换为QVariantList类型,而非原生JavaScript数组。在Qt 5.12版本中,Repeater直接使用这种QVariantList作为数据源时,无法通过modelData访问元素——它仅支持通过count获取长度,不支持直接遍历取值,因此抛出ReferenceError: modelData is not defined错误。
解决方案
提供两种可行的修复方式:
方案1:转换为原生JavaScript数组
将QVariantList转换为JS数组后,Repeater即可正常识别并使用modelData:
修改FieldDelegate.qml中的Repeater部分:
Repeater { model: Array.from(selectionColors) Rectangle { height: parent.height width: 20 color: modelData } }
方案2:通过索引直接访问元素
利用QVariantList支持索引取值的特性,直接通过Repeater的index访问颜色值:
修改FieldDelegate.qml中的Repeater部分:
Repeater { model: selectionColors.count Rectangle { height: parent.height width: 20 color: selectionColors[index] } }
额外说明
两种方案都能解决色块显示问题,选择哪种取决于你的业务场景:
- 方案1更贴近原生JS数组的使用习惯,后续若需对颜色列表做数组操作(如过滤、排序)更方便;
- 方案2无需类型转换,性能略优,适合仅需遍历展示的场景。
内容的提问来源于stack exchange,提问作者Thalia
相关产品推荐
相关产品推荐

