编辑QTableView单元格值

2 投票
1 回答
4735 浏览
提问于 2025-04-17 08:14

我该如何让 QTableView 的单元格在编辑时保持原来的值?当我开始编辑单元格时,它会自动被清空。我到处搜索,但找不到任何有用的线索。以下是我实现的模型视图:

class BlockViewModel(QAbstractTableModel):

    def __init__(self, structure, data):
        QAbstractTableModel.__init__(self)
        self._data = data
        self._struct = structure

        for i, s in enumerate(structure):
            cmnt = s['comment']
            name = cmnt if cmnt else s['name']
            self.setHeaderData(i, Qt.Horizontal, name)

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def columnCount(self, parent = QModelIndex()):
        return len(self._struct)

    def data(self, index, role):
        if role == Qt.DisplayRole:
            try:
                row = index.row()
                col = index.column()
                name = self._struct[col]['name']
                return self._data[row][name]
            except:
                pass
        elif role == Qt.CheckStateRole:
            return None

        return None

    def flags(self, index):
        flags = super(self.__class__,self).flags(index)

        flags |= Qt.ItemIsEditable
        flags |= Qt.ItemIsSelectable
        flags |= Qt.ItemIsEnabled
        flags |= Qt.ItemIsDragEnabled
        flags |= Qt.ItemIsDropEnabled

        return flags

    def headerData(self, section, orientation, role = Qt.DisplayRole):
        if role != Qt.DisplayRole:
            return None

        if orientation == Qt.Horizontal:
            cmnt = self._struct[section]['comment']
            return cmnt if cmnt else self._struct[section]['name']
        else:
            return str(section)

    def setData(self, index, value, role=Qt.EditRole):
        row = index.row()
        col = index.column()
        name = self._struct[col]['name']
        self._data[row][name] = value
        self.emit(SIGNAL('dataChanged()'))
        return True

1 个回答

9

data 方法负责一直显示你的数据。在编辑的时候,它会使用 EditRole。所以你需要修改你的 data 方法,让它在 EditRole 下显示的值和在 DisplayRole 下显示的一样,像下面这样:

def data(self, index, role):
    if role == Qt.DisplayRole or role == Qt.EditRole:
        try:
            row = index.row()
            col = index.column()
            name = self._struct[col]['name']
            return self._data[row][name]
        except:
            pass
    elif role == Qt.CheckStateRole:
        return None

    return None

撰写回答