qt - QML ItemDelegate 突出显示的属性不起作用

标签 qt hover qml highlight qitemdelegate

我想在 ItemDelegate 中自定义突出显示颜色。如果我使用默认的 ItemDelegate 和 Material 主题,那么当我将鼠标悬停在该项目上时,一切正常并且颜色会发生变化,但是当我重新定义背景时,它会崩溃并且颜色不再改变。

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属性不起作用?我如何定制这种颜色?

最佳答案

问题很简单,高亮属性不是从头创建的,必须激活它,而且最常见的是它与ListView.isCurrentItem有绑定(bind),所以必须更新当前项目:

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"
    }
}

ma​​in.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
            }
        }
    }
}

关于qt - QML ItemDelegate 突出显示的属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51912849/

相关文章:

c++ - Qt5 QMainWindow组件删除

css - 如何设置表格每隔一行的背景色并在悬停时突出显示行?

qt - 无法在 ApplicationWindow 中使用状态

javascript - QML/JS/REST 认证表单

python - 从 QML 访问 qresource 文件中的图像

c++ - 如何QDialograise()函数不起作用?

c++ - 如何在 Qt 中使用 Windows 网络 API?

qt - Qml ListView 空行占位符就像 TableView 中一样

css - Vuetify v-list-item 悬停时样式更改

jquery - 使用 jquery 更改缩略图的不透明度