python - 如何使用 pyside 在 QtableView 单元格中设置数据

标签 python pyside2 qtableview

我正在尝试在 QtableView 的单元格中设置一个值。我正在使用 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)

我正在努力解决的是如何理解如何将索引作为参数传递,我有行和列,关于如何正确执行此操作有任何帮助吗?

最佳答案

您需要使用 model.index(row, column,parent=None) (请参阅 documentation )来获取适当的 QModelIndex .
如果模型是二维的(不是 TreeView ),则不需要父级:

model.setData(model.index(row, column), value)

关于python - 如何使用 pyside 在 QtableView 单元格中设置数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65219705/

相关文章:

python - PyQt Webkit 和 html 表单 : Fetching output and closing window

python - 添加一个小部件(QProgressbar)作为 QTreeView 中的子项

python - 如何防止 QTableView 项在双击时被清除

python - 在尊重其索引结构的同时对多索引进行排序

python - 尝试用反转的匹配捕获组替换与 pandas 数据框中的模式匹配的所有值

python - 使用 PyInstaller 打包后 PySide2 应用程序中的路径错误

c++ - 如何从函数传递 QStandardItemModel?

c++ - 更改垂直标题标题

python - 在 ipython 中的网络驱动器上导入 numpy 失败

python - 从 pyuic5 转换的 Python 代码显示 PySide2 UI