无法引用ListView突出显示的内容

时间:2018-08-30 09:12:30

标签: listview reference qml

就像标题中所说的那样,我遇到一个问题:我有一个ListView,一个普通的delegate和一个highlight

在我的突出显示内,我在Text中放置了一个id组件,以便我可以引用它。

所以行为应该是这样的:我将ListView的项目移动通过,然后在键盘上按数字时,highlight内的文本应显示出来。

但是任何时候我尝试使用上述Text组件(像id一样被textComponent.text = "123"引用),都会得到ReferenceError: textComponent is not defined

我浏览了文档,但没有发现与无法通过id突出显示内容有关的任何内容。

有人知道这是什么原因吗,还是根本不支持这种行为?

我没有提供任何代码,因为该问题易于解释和重现,但是如果有人需要,我很乐意提供一小段内容。

编辑 代码

  ListView
    {
        height: 500
        width: 500

        model: ListModel { id: channelListModel }

        highlightMoveDuration: 200
        highlightRangeMode: ListView.ApplyRange
        snapMode: ListView.SnapToItem

        preferredHighlightBegin: height * 0.2
        preferredHighlightEnd: height * 0.8

        delegate: Item
        {
            id: channelItem
            width: ListView.view.width * 0.96
            height: parent.height

            Text
                {
                    anchors.fill: parent
                    text: "generic row text"
                }
        }

        Keys.onPressed:
        {
            switch(event.key)
            {
                case Qt.Key_0:
                case Qt.Key_1:
                case Qt.Key_2:
                case Qt.Key_3:
                case Qt.Key_4:
                case Qt.Key_5:
                case Qt.Key_6:
                case Qt.Key_7:
                case Qt.Key_8:
                case Qt.Key_9:
                    textComponent.text = event.key
             }
         }

        highlight: Rectangle
        {
            id: highlight
            color: "#40ffffff"

            Text
                {
                    id: textComponent
                    anchors.fill: parent
                }
         }

1 个答案:

答案 0 :(得分:2)

如果您查看ListView的文档,就会发现type of the property highlightComponent

Component总是为id创建一个新的上下文,就像在另一个文件中一样。 这意味着您无法从外部访问id内部的Component。组件可能已被实例化多次或根本没有实例化-因此id不会是唯一的。

您能做什么?

property中创建一个ListView,然后从组件内部读取它。

ListView {
    id: myListView
    ...
    property string hightlightText

    highlight: SomeItem { // Will be automatically transformed in a Component and initaly not fully created
        Text {
            text: myListView.highlightText // You can reference ids of the 'outside world'
        }
    }
}
相关问题