如何从QTreeview中删除所有行和子行

How to remove all rows and child rows from QTreeview

本文关键字:删除 QTreeview      更新时间:2023-10-16

我不知道为什么我有麻烦从qtreeview删除所有行和子行

我使用QStandardItemModel作为模型。现在这是我的代码不能工作。

有什么问题吗?

QModelIndex FirstQModelIndex;
QModelIndex parentQModelIndex;
int iMdlChidCound = m_model->hasChildren();
if(iMdlChidCound > 0)
{
    // only if there at list 1 row in the view 
    FirstQModelIndex = m_model->item(0,0)->index();
    QStandardItem* feedItem = m_model->itemFromIndex(FirstQModelIndex);
    // get the parent of the first row its the header row 
    QStandardItem* parentItem = feedItem->parent();

    // here im getting exception 
    int parent_rows= parentItem->hasChildren();
    parentQModelIndex = m_model->indexFromItem(parentItem);

    // now i like to delete all the rows under the header , and its dosnt work 
    if(parent_rows>0)
    {
        bool b = feedItem->model()->removeRows(0,y,parentQModelIndex);
    }
}

看起来你做的很多事情都是多余的。如果您的唯一目标是从模型中删除所有行,那么您可能只需要使用QStandardItemModel::clear

在你的代码中,你以一种你不必的方式在模型和项目之间跳转。

if(m_model->hasChildren()) {
    m_model->removeRows(0, m_model->rowCount());
}

应该能满足你的要求。

QStandardItemModel::clear()

清除包括标题行在内的所有项