Search code examples
qthoverqmlhighlightqitemdelegate

QML ItemDelegate highlighted property not work


I want to customize highlight color in ItemDelegate. If I use default ItemDelegate with Material theme then all ok and color change when i hover over this item, but when I redefine background it breaks down and colors not change anymore.

MyItemDelegate.qml:

import QtQuick 2.11
import QtQuick.Controls.Material 2.4
import QtQuick.Controls 2.4
import QtQuick.Templates 2.4 as T

T.ItemDelegate {
    id: myItemDelegate
    height: 40     
    anchors.left: parent.left
    anchors.right: parent.right

    contentItem: Text {
            text: "Hello"
            anchors.fill: parent
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
        }
    }

    background: Rectangle {
        anchors.fill: myItemDelegate
        color: myItemDelegate.highlighted ? "blue" : "transparent"
    }
}

Why highlighted property not work? And how I can customize this color?


Solution

  • The problem is simple, the highlighted property is not created from scratch, you must activate it, and the most common is that it has a binding with ListView.isCurrentItem, so you must update the currentItem:

    MyItemDelegate.qml

    import QtQuick 2.11
    import QtQuick.Controls.Material 2.4
    import QtQuick.Controls 2.4
    import QtQuick.Templates 2.4 as T
    
    T.ItemDelegate {
        id: myItemDelegate
        height: 40
        anchors.left: parent.left
        anchors.right: parent.right
        highlighted: ListView.isCurrentItem // <---
        contentItem: Text {
            text: "Hello"
            anchors.fill: parent
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
        }
        background: Rectangle {
            anchors.fill: myItemDelegate
            color: myItemDelegate.highlighted ? "blue" : "transparent"
        }
    }
    

    main.qml

    import QtQuick 2.9
    import QtQuick.Controls 2.2
    
    ApplicationWindow {
        visible: true
        width: 640
        height: 480
        title: qsTr("Scroll")
        ListView {
            id: listView
            anchors.fill: parent
            model: 20
            delegate: MyItemDelegate {
                MouseArea{
                    anchors.fill: parent
                    hoverEnabled: true
                    onHoveredChanged: listView.currentIndex = index
                }
            }
        }
    }