簡體   English   中英

removeRows()和QPersistentModelIndex

[英]removeRows() and QPersistentModelIndex

我已經實現了基於std::vectorQAbstractListModel 我現在想在QGraphicsScene顯示此模型的內容。 為此,我實現了自己的QGraphicsItem ,它存儲了一個QPersistentModelIndex作為指向數據的指針。

我已經實現了removeRows方法,如下所示:

bool VectorModel::removeRows(int row, int count, const QModelIndex& parent) {
    if (row + count < _vector.size()) {
        beginRemoveRows(QModelIndex(), row, row + count);
        _vector.erase(_vector.begin() + row, _vector.begin() + row + count);
        endRemoveRows();
        return true;
    }
    return false;
}

現在,由於我刪除了某些元素,因此以下元素的索引將更改。 因此,需要調整QPersistentModelIndex

我已經在QAbstractItemModel找到了changePersistentIndex()方法,並且知道可以使用persistentIndexList()獲得所有持久性索引。 但是我不知道如何使用這種方法相應地調整指標。 如何才能做到這一點?

更改這些索引是否足以防止Invalid index錯誤?

更新

我已使用@Sebastian Lange的增強功能更改了removeRows() ,但是它仍無法按預期工作,並且收到Invalid index錯誤:

bool LabelModel::removeRows(int row, int count, const QModelIndex& parent) {
    Q_UNUSED(parent)
    if (row + count < _vector.size()) {
        beginRemoveRows(QModelIndex(), row, row + count);
        _vector.erase(_vector.begin() + row, _vector.begin() + row + count);
        endRemoveRows();

        auto pil = persistentIndexList();
        for(int i = 0; i < pil.size(); ++i)
        {
            if (i >= row + count) {
                changePersistentIndex(pil[i], pil[i-count]);
            }
        }
        return true;
    }
    return false;
}

發出的錯誤如下所示(刪除第7個元素時):

QAbstractItemModel::endRemoveRows:  Invalid index ( 7 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 8 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 9 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 10 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 6 , 1 ) in model QAbstractListModel(0x101559320)

好吧,您無需擺弄changePersistentIndex,調用beginRemoveRows和endRemoveRows將自動更新模型上當前存在的所有持久性索引。 刪除行之后,您唯一應具有的無效QPersistentModelIndex是實際上已刪除的行上的索引

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM