model如下:
class DictionaryTableModel(QtCore.QAbstractTableModel): def __init__(self, data, headers): super(DictionaryTableModel, self).__init__() self._data = data self._headers = headers def data(self, index, role): row = index.row() column = index.column() column_key = self._headers[column][0] # [['字典key','释义'],...] value = self._data[row][column_key] if role == Qt.DisplayRole: return value def rowCount(self, index): # The length of the outer list. return len(self._data) def columnCount(self, index): # The length of our headers. return len(self._headers) def headerData(self, section, orientation, role): # section is the index of the column/row. if role == Qt.DisplayRole: if orientation == Qt.Horizontal: return str(self._headers[section][1]) # [['参数代码','释义'],...] if orientation == Qt.Vertical: return str(section + 1) + ' ' def get_data_by_row(self, row): return self._data[row]
表格如下
data = [ {'VBELN': 11,'POSNR': 12}, {'VBELN': 21,'POSNR': 22}, {'VBELN': 31,'POSNR': 32} ] headers = [['VBELN', '货号'], ['POSNR', '项目']] self.model = DictionaryTableModel(data, headers) self.tableView.setModel(self.model)
在点击表格行头后,一整行被选中,尝试使用self.tableView.currentIndex().row()获取行号时,选中第0行但是获取不到row,问题出在哪? 另外,在不选中任意一行的情况下,currentIndex().row()默认为最后一行,如何修改默认为None
![]() | 1 justou 2022-02-21 09:11:35 +08:00 你的代码不全, 应该贴一个完整的 demo, 拿来就能 debug 那种 1. 一整行被选中,尝试使用 self.tableView.currentIndex().row()获取行号应该是在一个 slot 中, 你是怎么写的? 2. 在不选中任意一行的情况下, currentIndex 是 invalid 的, row()返回-1 不是表示最后一行, 行索引的有效范围是[0, rowCount() - 1], 在处理一个 index 时注意使用 isValid()判断 |
![]() | &nbs; 2 6167 OP @justou 感谢提示,但是刚刚在整理代码的时候,突然发现昨天晚上的 bug 复现不出来了,currentIndex().row()也默认为-1 了 |
![]() | 3 imn1 2022-02-24 20:03:18 +08:00 表格的数据行的下标从 0 开始,标题行不计入 标题行是另一个"控件",有其自有的方法属性,要用 view.header()类似的方法提取这个控件 currentIndex 仅指光标当前的行,跟选择无直接关系,所以行号就是其实际值 你想获得选择的行(可以是多行)的第一个,不是用 currentIndex ,而是用 selectedIndexes/selectedItems 类似的方法 提醒一下,无论光标还是选择,行号都是该行的真实行号,并非多个选择中的排第几个 |