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

Qt Quick TableView单元格选中失效:currentRow/Column始终为-1求助

解决QtQuick 2.15 TableView单元格选中失效问题

核心问题分析

你遇到的currentRow/currentColumn始终为-1,是因为委托的MouseArea未正确关联TableView的选中逻辑,且QtQuick 2.15对应的QtQuick.Controls 1.x版本TableView需要手动绑定选中状态,不能依赖自动关联。另外cellAtPos/cellAtPosition是QtQuick.Controls 2.x+版本的API,在1.x中不支持,这就是你出现属性报错的原因。

具体修复方案

1. 修正TableView的选中配置

在Table_custom.qml中,开启选中模式并明确行为:

import QtQuick.Controls 1.4 // QtQuick 2.15对应Controls 1.4,勿混用2.x版本组件

TableView {
    id: tableView
    width: 600
    height: 400
    model: TableModelCustom {}
    delegate: Table_customDelegate {}

    // 启用单单元格选中模式
    selectionMode: TableView.SingleSelection
    selectionBehavior: TableView.SelectItems

    // 可选:监听选中变化用于调试
    onCurrentRowChanged: console.log("当前行:", currentRow)
    onCurrentColumnChanged: console.log("当前列:", currentColumn)
}

2. 改造委托的MouseArea逻辑

在Table_customDelegate.qml中,利用委托上下文自带的row和column属性,直接调用TableView的选中方法:

import QtQuick 2.15

Item {
    id: delegateItem
    width: tableView.columnWidthProvider(column)
    height: 40

    Text {
        text: model.display
        anchors.centerIn: parent
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            // 直接绑定当前选中行/列
            tableView.currentRow = row
            tableView.currentColumn = column
            // 执行选中操作
            tableView.select(row, column)
            // 调试输出
            console.log("点击行:", row, "点击列:", column)
        }
    }
}

3. 确保Model的正确性

TableModelCustom.qml需符合Controls 1.x TableView的角色要求:

import QtQuick 2.15

ListModel {
    ListElement { display: "第1行第1列" }
    ListElement { display: "第1行第2列" }
    ListElement { display: "第2行第1列" }
    ListElement { display: "第2行第2列" }

    // 自定义角色需明确声明(可选,默认display角色可省略)
    roleNames: {
        "display": "display"
    }
}

关键注意事项

  • 区分Controls版本:QtQuick 2.15同时存在Controls 1.x和2.x的TableView,两者API差异极大。你后续要结合PySide6,建议提前切换到QtQuick.Controls 2.15的TableView(Qt6兼容),避免迁移麻烦。若用2.x版本,选中逻辑需改用SelectionModel:
    import QtQuick.Controls 2.15
    
    TableView {
        id: tableView
        // ...其他配置
        selectionModel: ItemSelectionModel {
            model: tableView.model
        }
    
        delegate: Item {
            // ...
            MouseArea {
                onClicked: {
                    tableView.selectionModel.select(tableView.model.index(row, column), ItemSelectionModel.SelectCurrent)
                }
            }
        }
    }
    
  • 避免高版本API:QtQuick 2.15的1.x TableView没有cellAtPos这类方法,直接用委托的row/column属性即可获取单元格位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:13:10