Qt mvc二

53 篇文章 36 订阅

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

在我的例子代码中

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;
}

addmodel直接修改模型
void StringListModel::addmodel(const QString &c)
{
    insertRows(rowCount(QModelIndex()),1,QModelIndex());
    m_slist.replace(rowCount(QModelIndex())-1,c);
}

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

也可以这么来

void StringListModel::addmodel(const QString &c)
{
    // insertRows(rowCount(QModelIndex()),1,QModelIndex());
    insertRow(rowCount(QModelIndex()));
    m_slist.replace(rowCount(QModelIndex())-1,c);
}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值