Lv.的博客

qt mvc2

继续上次的例子,对于list才说只有行,讨论列是没有意义的。

bool insertRows(int row, int count, const QModelIndex &parent);
bool removeRows(int row, int count, const QModelIndex &parent);

在文档中,insertRows是这么写的,在支持这个操作的models中,在给定的row之前插入count数目的row到model中,插入的都是parent的孩子。

如果row=0,这些行被插入到parent存在的行,如果row=rowCount(),也是如此。如果parent无孩子,这些rows作为一个单列被插入。在最后明确强调了必须使用beginInsertRows和endInsertRows,所以在实现这个的时候,这两个函数才是关键,看这两个函数,这两个在QAbstractItemModel虚基类中是protect,所以他们只是工具函数。

首先beginInsertRows

void beginInsertRows(const QModelIndex &parent, int first, int last);参数first是rows开始处,last是结束处,所以是插入长度是last-first+1,这两个参数是有insertRows的row和count参数决定。

可是实际时,我们在插入行时,只是可以在原有的数据之后添加一些数据,所以first=现在的行数(行数从0开始,所以现在的行数就是新的行),last=first+count-1。

在我的例子代码中
[cpp] view plaincopyprint?
<span style="font-size:18px;">bool StringListModel::insertRows(int row, int count, const QModelIndex &/*parent*/)
{
beginInsertRows(QModelIndex(),row,row + count -1);
for (int i = 0;i < count;++i) {
//链表插入的时候,row大于size()时按size()来算
m_slist.insert(row,QString());
}
endInsertRows();
return true;
}</span>

addmodel直接修改模型
[cpp] view plaincopyprint?
<span style="font-size:18px;">void StringListModel::addmodel(const QString &c)
{
insertRows(rowCount(QModelIndex()),1,QModelIndex());
m_slist.replace(rowCount(QModelIndex())-1,c);
}</span>

现在insertRow的两个参数可以很好的理解了。

也可以这么来
[cpp] view plaincopyprint?
<span style="font-size:18px;">void StringListModel::addmodel(const QString &c)
{
// insertRows(rowCount(QModelIndex()),1,QModelIndex());
insertRow(rowCount(QModelIndex()));
m_slist.replace(rowCount(QModelIndex())-1,c);
}</span>

posted @   Avatarx  阅读(297)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示