首页 > 解决方案 > 通过 CheckBox 删除 QTableView/QAbstractTableModel 中的行

问题描述

我创建了一个表格视图,我试图通过单击表格视图中嵌入的复选框来删除行。当取消选中复选框时,我到达了它索引正确行的地步,但模型拒绝删除该行,而是返回“False”。有什么想法吗?从 tablewidgets 切换后对 tableviews 仍然是新的

class pandasModel(QAbstractTableModel):
    def __init__(self, data, check_col=[0, 0]):
        QAbstractTableModel.__init__(self)
        self._data = data
        self._check = check_col

        cs = 0
        if check_col[1]: cs = 2
        self._checked = [[cs for i in range(self.columnCount())] for j in range(self.rowCount())]

    def rowCount(self, parent=QModelIndex):
        return self._data.shape[0]

    def columnCount(self, parent=QModelIndex):
        return self._data.shape[1]



    def data(self, index, role):

        if index.isValid():
            data = self._data.iloc[index.row(), index.column()]

            if role == Qt.DisplayRole:
                if isinstance(data, float):
                    return f'{data:,.2f}'
                elif isinstance(data, (int, np.int64)):
                    return f'{data:,}'
                else:
                    return str(data)
            elif role == Qt.TextAlignmentRole:
                if isinstance(data, (float, int, np.int64)):
                    return Qt.AlignVCenter + Qt.AlignRight
            elif role == Qt.CheckStateRole:
                if self._check[0] > 0:
                    if self._check[0] == index.column():
                        return self._checked[index.row()][index.column()]

        return None

    def flags(self, index):
        if not index.isValid(): return
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEditable

    def setData(self, index, value, role):
        if not index.isValid() or role != Qt.CheckStateRole: return False
        self._checked[index.row()][index.column()] = value
        if value == 0:
            print('checked')
            self.removeRow(index.row()) #THIS IS WHERE IT RETURNS FALSE
        self.dataChanged.emit(index, index)
        return True

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]

        return None

标签: pythonpyqtpyqt5qtableviewqabstracttablemodel

解决方案


推荐阅读