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

如何将Qt ListView中的指定列表项设置为不可选中?

实现ListView特定列表项不可选中的极简方案

要让ListView中索引为2的项不可选中,核心从交互拦截和样式区分两方面入手,以下是修改后的完整代码,直接替换你的原代码即可:

Window {
    id: mainWindow
    width: 130
    height: 240
    visible: true
    title: qsTr("Hello")

    Rectangle {
        id: bg
        color: "#ffffff"
        anchors.fill: parent
    
        ListModel {
            id: nameModel
            ListElement { name: "Alice" }
            ListElement { name: "Bob" }
            ListElement { name: "Jay" } // 索引2的目标项
            ListElement { name: "Kate" }
        }

        Component {
            id: nameDelegate
            Item {
                width: parent.width
                height: 30 // 固定高度确保交互区域统一

                // 标记当前项是否可选中
                property bool isSelectable: model.index !== 2

                Text {
                    anchors.centerIn: parent
                    text: model.name
                    font.pixelSize: 24
                    // 不可选项用灰色区分状态
                    color: isSelectable ? "black" : "#999999"
                }

                MouseArea {
                    anchors.fill: parent
                    // 仅允许可选中项响应点击
                    enabled: isSelectable
                    onClicked: listView.currentIndex = model.index
                }
            }
        }

        ListView {
            id: listView
            anchors.fill: parent
            model: nameModel
            delegate: nameDelegate
            clip: true
            highlight: Rectangle {
                anchors { left: parent.left; right: parent.right }
                height: 30
                color: "lightgrey"
            }

            // 拦截键盘导航选中不可选项的情况
            onCurrentIndexChanged: {
                if (currentIndex === 2) {
                    // 恢复到上一个选中项,无历史选中则设为-1(无选中状态)
                    currentIndex = previousIndex !== undefined ? previousIndex : -1
                } else {
                    previousIndex = currentIndex
                }
            }
            property int previousIndex: -1
        }
    }
}

关键实现说明

  1. delegate层拦截点击:通过isSelectable属性判断当前项索引,用MouseArea控制仅可选中项响应点击操作,同时修改文本颜色直观区分状态。
  2. ListView层拦截键盘选中:监听currentIndexChanged事件,若选中不可选项则恢复到上一个有效选中项,避免键盘导航绕过点击拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:55:31