Search code examples
qtlistviewqmlhighlightreferenceerror

Unable to reference highlight id of listview qml


I have a listview highlight component whose id I need to use outside of this component(both inside and outside listview) but whatever I try I get a reference error: Id is not defined. Unable to find a workaround for this. I read somewhere that since type of highlight is component, it can't be used outside of it. But I really need to use this id outside. Could anyone help pls A small outline of the code I have at the moment is

ListView {
    id: listId
    MouseArea {
        anchors.fill: parent
        onClicked: {
            boxId.visible = false
        } //unable to use 'boxId' like this. Getting reference error
    }

    delegate: Rectangle {}

    highlight: Rectangle {
        id: boxId
    }
}


Solution

  • The problem is the item in highlight does not always exist when you try to access it in in MouseArea. For that reason it cannot be referenced directly from this scope.

    You could try something like this to only access it when it exists:

    ListView {
        id: listId
        MouseArea {
            anchors.fill: parent
            onClicked: {
                var item = ListView.highlightItem
    
                if (item) {
                    item.visible = false
                }
            }
        }
    
        delegate: Rectangle {}
    
        highlight: Rectangle {
            id: boxId
        }
    }