Qt mvc二

来源:互联网 发布:自然堂 淘宝销售额 编辑:程序博客网 时间:2024/05/22 05:02

继续上次的例子,对于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?
  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直接修改模型
[cpp] view plaincopyprint?
  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的两个参数可以很好的理解了。

也可以这么来

[cpp] view plaincopyprint?
  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 0
原创粉丝点击