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

Qt6 QTableView如何遍历选中行的列名与值并生成字典

获取QTableView选中行的列名与值并生成字典

要实现选中行数据转字典的需求,核心是通过模型的headerData()方法获取列名,结合单元格值构建键值对。以下是具体实现方案:

1. 修改点击事件处理函数

更新你的qTableViewSingleRowSelection方法,加入列名与值的获取逻辑:

from PyQt5.QtCore import Qt

def qTableViewSingleRowSelection(self, clickedIndex):
    row = clickedIndex.row()
    print("Selected Row: {0}".format(row))
    self.tblView.selectRow(row)
    
    # 初始化存储字典
    row_data_dict = {}
    model = self.tblView.model()
    column_count = model.columnCount()
    
    # 遍历每一列,构建列名-值的字典
    for col in range(column_count):
        # 获取当前列的名称
        column_name = model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
        # 获取当前单元格的索引
        cell_index = model.index(row, col)
        # 获取单元格显示值
        cell_value = model.data(cell_index, Qt.DisplayRole)
        # 存入字典
        row_data_dict[column_name] = cell_value
    
    print("选中行数据字典:", row_data_dict)
    
    # 准备转置数据(用于新QTableView显示)
    transposed_data = [[key, value] for key, value in row_data_dict.items()]
    # 后续可将transposed_data传入新的TableModel,绑定到新QTableView实现转置展示

2. 确保自定义TableModel正确返回列名

如果你的TableModel是自定义的,需要确保它重写了headerData方法以返回正确列名,示例如下:

from PyQt5.QtCore import QAbstractTableModel, Qt

class TableModel(QAbstractTableModel):
    def __init__(self, data, headers=None, parent=None):
        super().__init__(parent)
        self._data = data
        # 初始化表头,若未传入则默认生成"Column 1"格式的列名
        self._headers = headers if headers else [f"Column {i+1}" for i in range(len(data[0]))]
    
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        # 返回水平方向的表头文本(列名)
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return self._headers[section]
        return super().headerData(section, orientation, role)
    
    # 实现其他必要方法(rowCount、columnCount、data)...

关键逻辑说明

  • model.headerData(col, Qt.Horizontal, Qt.DisplayRole):获取水平方向(列)的表头文本,即列名。
  • model.index(row, col):创建对应行和列的索引对象,用于定位单元格。
  • model.data(cell_index, Qt.DisplayRole):获取单元格的显示值,与表格中展示的内容一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:41:04