QT C++ QStandardItemModel类的insertRows实现源码
时间: 2024-03-06 13:50:32 浏览: 130
`QStandardItemModel` 类的 `insertRows` 函数的实现源码如下:
```cpp
bool QStandardItemModel::insertRows(int row, int count, const QModelIndex &parent)
{
Q_D(QStandardItemModel);
QModelIndex parentIndex = parent.isValid() ? parent : QModelIndex();
QStandardItem *parentItem = itemFromIndex(parentIndex);
if (!parentItem)
parentItem = invisibleRootItem();
QStandardItem *item = parentItem->child(row, 0);
bool success = d->insertRows(row, count, parentIndex);
if (success) {
for (int i = 0; i < count; ++i) {
QStandardItem *newItem = new QStandardItem;
parentItem->setChild(row + i, 0, newItem);
}
if (item && item->rowCount() > 0) {
for (int i = item->rowCount() - 1; i >= 0; --i) {
QStandardItem *oldChild = item->takeChild(i, 0);
QStandardItem *newChild = item->child(row + count + i, 0);
if (newChild)
delete newChild;
item->setChild(row + count + i, 0, oldChild);
}
}
emit rowsInserted(parentIndex, row, row + count - 1);
}
return success;
}
```
这个函数用于插入一定数量的行到模型中。它接受三个参数:`row` 表示要插入的第一行的索引,`count` 表示要插入的行数,`parent` 表示父项的索引。
这个函数的实现首先通过 `itemFromIndex` 函数获取父项对应的 `QStandardItem` 对象,如果父项无效,则使用根节点 `invisibleRootItem()` 作为父项。接着,它在父项中查找第一行,以便在该行之前插入新行。然后,它调用 `QStandardItemModelPrivate` 类的 `insertRows` 函数插入行,如果插入成功,则创建新的 `QStandardItem` 对象并将其添加到父项中。最后,它发出 `rowsInserted` 信号,通知视图模型的行已经被插入。
需要注意的是,`insertRows` 函数并不是线程安全的,因此您应该在主线程中调用它,或者使用 `QMetaObject::invokeMethod` 函数来在主线程中调用它。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)