You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Repeater中ListView可见性控制异常,报undefined转bool错误求助

解决QML中ListView可见性绑定的"Unable to assign [undefined] to bool"错误

错误根源在于Repeater delegate内的模型引用错误:buttonRepeater.model指向的是整个groupModel列表,而非当前迭代的单个ListElement,所以buttonRepeater.model.expanded会返回undefined,无法赋值给bool类型的visible属性。

修正方案

调整两处模型引用,直接使用delegate内部的model对象(它会自动指向当前迭代的groupModel项):

  • 将ListView的visible属性从buttonRepeater.model.expanded改为model.expanded
  • 将ListView的模型判断条件中的buttonRepeater.model.name改为model.name

修正后的完整代码

import QtQuick
import QtQuick.Controls

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    ListModel {
        id: groupModel
        ListElement {
            name: "Model 1"
            expanded: false
        }
        ListElement {
            name: "Model 2"
            expanded: false
        }
        ListElement {
            name: "Model 3"
            expanded: false
        }
    }

    ListModel {
        id: model1Items
        ListElement { description: "Item 1.1" }
        ListElement { description: "Item 1.2" }
        ListElement { description: "Item 1.3" }
    }

    ListModel {
        id: model2Items
        ListElement { description: "Item 2.1" }
        ListElement { description: "Item 2.2" }
        ListElement { description: "Item 2.3" }
    }

    ListModel {
        id: model3Items
        ListElement { description: "Item 3.1" }
        ListElement { description: "Item 3.2" }
        ListElement { description: "Item 3.3" }
    }

    Column {
        anchors.fill: parent
        spacing: 10

        Repeater {
            id: buttonRepeater
            model: groupModel

            delegate: Column {
                width: parent.width

                Button {
                    text: model.name
                    onClicked: {
                        groupModel.setProperty(index, "expanded", !model.expanded)
                    }
                }

                ListView {
                    id: listView
                    width: parent.width
                    height: contentHeight
                    visible: model.expanded
                    model: model.name === "Model 1" ? model1Items :
                           model.name === "Model 2" ? model2Items :
                           model3Items

                    delegate: Item {
                        width: parent.width
                        height: 30

                        Text {
                            anchors.centerIn: parent
                            text: model.description
                        }
                    }
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者praveen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:27:19