QTreeWidget搜索并隐藏不匹配的项

QTreeWidget可以呈现出数据的层次关系,有时需要对数据进行筛选,只显示结果项,其他项隐藏。如下图所示

QTreeWidget搜索并隐藏不匹配的项_第1张图片
QTreeWidget搜索并隐藏不匹配的项_第2张图片
通过查询QTreeWidget的方法可以看到有个setRowHidden方法可以隐藏行,Qt assistant中说明如下:

void QTreeView::setRowHidden(int row, const QModelIndex &parent, bool hide)
If hide is true the row with the given parent is hidden, otherwise the row is shown.

注意这是隐藏parent节点下面第row项。现在问题转化为获取需隐藏项的parent的QmodelIndex和该项在parent中的row,再次查找方法可以发现有个indexFromItem方法,Qt assistant中说明如下:

[protected] QModelIndex QTreeWidget::indexFromItem(const QTreeWidgetItem *item, int column = 0) const
Returns the QModelIndex associated with the given item in the given column.

这是个protected方法,QTreeWidget对象无法直接调用,我们必须自定义TreeWidget类继承QTreeWidget类,然后覆写indexFromItem方法成public的,在自定义TreeWidget类中直接返回QTreeWidget::indexFromItem()

//ctreewidget.h
class CTreeWidget : public QTreeWidget
{
public:
    CTreeWidget(QWidget* parent = NULL);
    QModelIndex indexFromItem(QTreeWidgetItem *item, int column = 0) const;
};

//ctreewidget.cpp
QModelIndex CTreeWidget::indexFromItem(QTreeWidgetItem *item, int column) const
{
    return QTreeWidget::indexFromItem(item, column);
}

如此我们就可以调用indexFromItem方法获得一个QTreeWidgetItem*的QModelIndex
搜索结果并隐藏不匹配的结果,代码如下

void Widget::onSearch(const QString& text)
{
    if (text.isEmpty())	//显示全部
    {
        for (int i = 0; i< m_pTreeWidget->topLevelItemCount(); ++i)
        {
            QTreeWidgetItem* topItem = m_pTreeWidget->topLevelItem(i);
            m_pTreeWidget->setRowHidden(i,m_pTreeWidget->indexFromItem(topItem->parent()),false);
        }
    }
    QList resultList = m_pTreeWidget->findItems(text, Qt::MatchContains);	//搜索结果
    if (resultList.size() > 0)
    {
        for (int i = 0; i< m_pTreeWidget->topLevelItemCount(); ++i)
        {
            QTreeWidgetItem* topItem = m_pTreeWidget->topLevelItem(i);
            if (resultList.contains(topItem))
                m_pTreeWidget->setRowHidden(i,m_pTreeWidget->indexFromItem(topItem->parent()),false);	//显示匹配的结果
            else
                m_pTreeWidget->setRowHidden(i,m_pTreeWidget->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
        }
    }
}

你可能感兴趣的:(Qt)