Qt Qtableview 自定义model继承QAbstractTableModel 重写insertRows
时间: 2023-07-21 20:25:38 浏览: 99
如果你想重写insertRows()函数来实现动态添加数据到自定义的QAbstractTableModel子类中,可以按照以下方式进行操作:
```python
class MyTableModel(QAbstractTableModel):
def __init__(self, data, header):
super().__init__()
self._data = data
self._header = header
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return len(self._header)
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self._header[section]
def insertRows(self, row, count, parent=QModelIndex()):
self.beginInsertRows(parent, row, row + count - 1)
for i in range(count):
self._data.insert(row + i, [None] * self.columnCount())
self.endInsertRows()
return True
```
在这个示例中,我们重写了insertRows()函数。这个函数接受三个参数:行号、要插入的行数和父索引。它使用beginInsertRows()和endInsertRows()函数来通知视图进行更新,并在_data列表中插入新行。在这个示例中,我们将新行初始化为包含空值的列表。最后,函数返回True以表示插入操作已成功完成。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)