python - How to SetData in a QtableView Cell using pyside
问题描述
I'm trying to set a value in a cell in my QtableView. I'm using Pyside2.
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, mlist=None):
super(TableModel, self).__init__()
self._items = [] if mlist == None else mlist
self._header = []
def data(self, index, role = QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return self._items[index.row()][index.column()]
return None
def setData(self, index, value, role = QtCore.Qt.EditRole):
if value is not None and role == QtCore.Qt.EditRole:
self._items[index.row()][index.column()] = value
return True
return False
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
# skip the irrelevant code #
Table = QTableView()
model = TableModel()
Table.setModel(model)
row, column = a_function_that_outputs_the_row_and_column_of_the_cell_to_edit()
self.Table.model().setData(index ?, value)
What I'm struggling with is getting to understand how to pass the index as an argument, I have the row and column, any help on how to do that properly?
解决方案
You need to use model.index(row, column, parent=None)
(see the documentation) to get the appropriate QModelIndex.
If the model is two dimensional (not a tree view), the parent is not required:
model.setData(model.index(row, column), value)
推荐阅读
- pycharm - 找不到 SAM CLI 可执行文件 - Pycharm
- angular - 生成角度组件时 src/app 前缀来自哪里
- python - TypeError:“管道”对象在自定义分类器中不可调用
- mysql - MySQL 请求 - 在有 1000 条记录的数据库上运行非常缓慢
- java - 在 android studio 4.1 更新中无法将矢量添加到项目中
- python - 在 kubernetes pod 上安装 Pip 失败
- python - _tkinter.TclError:项目 1 已经存在于 tkinter 树视图中
- visual-c++ - 如何在 CWinApp::ExitInstance() 上打开模式对话框
- python - 使用正则表达式从多行字符串中找到最短的匹配项
- c# - 获取可用数量少于需要的物品