You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QML ListView选中项点击后无法高亮的问题

解决ListView点击项不高亮的问题

你的代码中点击ListView项时仅打印了文件名,但未将点击的项设置为ListView的currentItem,导致ListView.isCurrentItem的判断始终不成立,所以选中项不会高亮。

只需在MouseArea的onClicked事件中添加设置当前选中索引的代码即可修复:

import QtQuick
import QtQuick.Controls

Window {
    visible: true
    width: 400
    height: 400
    color: "white"

    property string filelist: '{"files":[{"name":"file1.txt","size":1024,"type":"file"},{"name":"file2.jpg","size":2048,"type":"file"},{"name":"directory1","type":"directory"},{"name":"file3.docx","size":5120,"type":"file"},{"name":"directory2","type":"directory"}]}'

    ListView {
        anchors.fill: parent
        model: JSON.parse(filelist).files // Parse the JSON string into a model

        delegate: Item {
            width: ListView.view.width
            height: 50

            Rectangle {
                width: parent.width
                height: parent.height
                anchors.fill: parent
                // 选中时蓝色背景,未选中透明
                color: ListView.isCurrentItem ? "blue" : "transparent"

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        console.log(modelData.name)
                        // 设置当前项为ListView的选中项
                        ListView.view.currentIndex = index
                    }
                }

                Image {
                    id: iconImage
                    width: 24
                    height: 24
                    anchors.verticalCenter: parent.verticalCenter
                    source: modelData.type === 'file' ? "file-icon.png" : "directory-icon.png"
                }

                Text {
                    text: modelData.name
                    anchors.verticalCenter: iconImage.verticalCenter
                    anchors.left: iconImage.right
                    anchors.leftMargin: 10
                    // 选中时文字变白,提升可读性
                    color: ListView.isCurrentItem ? "white" : "black"
                }
            }
        }
    }
}

关键说明

  • ListView.view.currentIndex = index:将点击的delegate对应的索引设置为ListView的当前选中索引,触发ListView.isCurrentItem的状态变化。
  • 额外优化了文字颜色,选中时变为白色,避免蓝色背景下文字看不清。

内容的提问来源于stack exchange,提问作者noob_user

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 12:20:10