QAbstractTableModel 插入行 insertRows 出现'numpy.ndarray' object has no attribute 'insert'错误
时间: 2023-07-31 22:06:05 浏览: 60
非常抱歉给你带来困惑。你是正确的,`'numpy.ndarray' object has no attribute 'insert'`错误是因为在numpy数组上调用了`insert()`方法,而numpy数组没有`insert()`方法。
为了在QAbstractTableModel中插入行,你可以使用Python的内置列表(list)而不是numpy数组。下面是修改后的示例代码:
```python
from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex
from PyQt5.QtWidgets import QApplication, QTableView
class MyTableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self.data = data
def rowCount(self, parent=QModelIndex()):
return len(self.data)
def columnCount(self, parent=QModelIndex()):
return len(self.data[0])
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole or role == Qt.EditRole:
return self.data[index.row()][index.column()]
return None
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.EditRole:
self.data[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
return False
def flags(self, index):
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
def insertRows(self, position, rows, parent=QModelIndex()):
self.beginInsertRows(parent, position, position+rows-1)
for _ in range(rows):
self.data.insert(position, [''] * self.columnCount())
self.endInsertRows()
return True
if __name__ == '__main__':
app = QApplication([])
data = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
model = MyTableModel(data)
view = QTableView()
view.setModel(model)
view.show()
# 插入一行
model.insertRows(1, 1)
app.exec_()
```
在这个修改后的代码中,我们将数据存储在Python的内置列表中。在`insertRows()`方法中,我们使用Python列表的`insert()`方法来插入新的空行。
现在,你可以在QAbstractTableModel中成功使用`insertRows()`方法来插入行,而不会再出现`'numpy.ndarray' object has no attribute 'insert'`错误。