我要自定义ItemDelegate
中的突出显示颜色。如果我在材质主题上使用默认的ItemDelegate
,那么当我将鼠标悬停在此项目上时,所有的确定和颜色都会更改,但是当我重新定义背景时,它会分解并且颜色不再更改。
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"
}
}
为什么highlighted
属性不起作用?以及如何自定义此颜色?
答案 0 :(得分:0)
问题很简单,突出显示的属性不是从头创建的,必须激活它,最常见的是它与ListView.isCurrentItem
绑定,因此必须更新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
}
}
}
}