Lisa Vitolo
Lisa Vitolo

Reputation: 51

ListView highlight item isn't shown

I'm trying to highlight the currently selected item in a ListView. Below is the code I'm using; for some reason, while a similar code works perfectly in another ListView of this application, here the SelectedRectangle item is never displayed, althought the selected item changes when it should.

Rectangle {
    id: deviceTree
    width: (window.width * 2) / 3
    height: 400

    border {
        width: 2
        color: "black"
    }

    ListView {
        id: deviceTreeView

        model: deviceTreeModel
        delegate: deviceTreeDelegate
        highlight: SelectionRectangle {}

        anchors.fill: parent
        anchors.margins: 6
    }

    Component {
        id: deviceTreeDelegate

        Rectangle {
            border.color: "#CCCCCC"
            width: deviceTree.width
            height: 30

            smooth: true
            radius: 2

            MouseArea {
                anchors.fill: parent
                onClicked: { deviceTreeView.currentIndex = index; window.selectedDeviceChanged(deviceName) }
            }
        }
    }
}

SelectedRectangle.qml

Rectangle
{
    id: selectionRectangle

    color: "lightsteelblue"
    smooth: true
    radius: 5
}

SOLUTION: The rectangle in deviceTreeDelegate was by default white and overlapped the selection rectangle. Using the property it's set as trasparent so that the selection can be seen.

Upvotes: 5

Views: 5331

Answers (2)

MartinJ
MartinJ

Reputation: 1701

This is due to the default Rectangle color being white and the highlight being stacked under the delegate. Setting the Rectangle color to "transparent" will allow the highlight to be visible through the delegate.

Upvotes: 13

air-dex
air-dex

Reputation: 4180

Your code gets two mistakes :

  1. The component for the highlight property. The name of the type of the component is the same than the name of the QML file where it is defined. You defined it in a file named SelectedRectangle.qml so you have to write highlight: SelectionRectangle {} in your main QML file
  2. The type of the highlight member is Component. So the component that you use for this member should have got a type which inherits Component. Or you use a QML component that inherits Rectangle and Rectangle does not inherit Component. You should enclose your SelectedRectangle in a Component object, just like you did for the delegate.

Finally, you should write something like this for your highlight component :

highlight: Component {
    SelectedRectangle {}
}

Upvotes: 0

Related Questions