【问题标题】:QML ItemDelegate highlighted property not workQML ItemDelegate 突出显示的属性不起作用
【发布时间】:2018-08-19 06:50:56
【问题描述】:

我想在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 属性不起作用?以及如何自定义这种颜色?

【问题讨论】:

    标签: qt hover qml highlight qitemdelegate


    【解决方案1】:

    问题很简单,高亮属性不是从头创建的,必须激活它,最常见的是它与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"
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2019-12-08
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2016-05-13
      相关资源
      最近更新 更多