首页 > 解决方案 > 为什么我的亮点项目快速显示和消失?

问题描述

我写了一个简单的ListView并且想在按下键盘箭头键时突出显示该项目。
程序看起来不错,但是高亮功能工作起来很奇怪,它快速显示并且在我眼中消失。这不是我想要的效果,我希望它在当前项目高亮时始终显示高亮颜色。

import QtQuick 2.15
import QtQuick.Window 2.15

Rectangle {
    width: 400
    height: 400

    Component {
        id: nameDelegate
        Rectangle {
            width: ListView.view.width
            height: 30

            Text {
                anchors.centerIn: parent
                text: index
                font.pixelSize: 14
            }
        }

    }

    ListView {
        anchors.fill: parent
        spacing: 5
        focus: true
        model: 10
        delegate: nameDelegate

        highlight: Rectangle {
            width: ListView.view.width
            height: ListView.view.currentItem.height
            color: "lightGray"
        }
    }

}

添加新信息
如果我将委托项目(矩形)更改为下面

Rectangle {
    width: ListView.view.width
    height: 30
    color: "#ada"
    Text {
        anchors.centerIn: parent
        text: index
        font.pixelSize: 14
    }
}

而且我想在按下箭头键时突出显示项目显示浅灰色,我该怎么做?

标签: qtqml

解决方案


这是因为堆叠顺序

高亮的默认z值为0. 每个委托的z值为1,因此默认情况下,突出显示在每个委托的后面。

您的代表有一个白色Rectangle作为其背景,因此突出显示将不可见。

您可以从代理中删除白色背景(例如,只使用普通的Item或将color矩形设置为透明)或增加高亮的 z 值。但是,后者将导致文本不可见,因此您必须重新考虑突出显示的外观。例如,您可以将其设置为下划线而不是纯色块:

ListView {
    anchors.fill: parent
    spacing: 5
    focus: true
    model: 10
    delegate: nameDelegate

    highlight: Item {
        z: 2
        Rectangle {
            width: parent.width
            height: 1
            y: parent.height - height
            color: "lightGray"
        }
    }
}

推荐阅读