Qt mvc二

9 篇文章 0 订阅

继续上次的例子,对于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。

在我的例子代码中

  1. <span style="font-size:18px;">bool StringListModel::insertRows(int row, int count, const QModelIndex &/*parent*/)  
  2. {  
  3.     beginInsertRows(QModelIndex(),row,row + count -1);  
  4.     for (int i = 0;i < count;++i) {  
  5.         //链表插入的时候,row大于size()时按size()来算  
  6.         m_slist.insert(row,QString());  
  7.     }  
  8.     endInsertRows();  
  9.     return true;  
  10. }</span>  

addmodel直接修改模型
  1. <span style="font-size:18px;">void StringListModel::addmodel(const QString &c)  
  2. {  
  3.     insertRows(rowCount(QModelIndex()),1,QModelIndex());  
  4.     m_slist.replace(rowCount(QModelIndex())-1,c);  
  5. }</span>  

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

也可以这么来

  1. <span style="font-size:18px;">void StringListModel::addmodel(const QString &c)  
  2. {  
  3.     // insertRows(rowCount(QModelIndex()),1,QModelIndex());  
  4.     insertRow(rowCount(QModelIndex()));  
  5.     m_slist.replace(rowCount(QModelIndex())-1,c);  
  6. }</span>  

insertRow内部实现就是使用的insertRows,我们插入之后只是默认值(这里是空字符串,你可以自己修改),所以我们必须把默认值换成我们需要的。在调用beginInsertRows时,它会发出rowsAboutToBeInserted,通知所有与这个model有关的视图更新,这也是必须使用这些函数的原因,不然只是修改了底层数据,而上层没反应。




转自:http://blog.csdn.net/zhx6044/article/details/9025657

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值