首页 > 解决方案 > 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?

标签: pythonpyside2qtableview

解决方案


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)

推荐阅读