QTreeWidget搜索并隐藏不匹配的项

本文介绍了如何在QTreeWidget中实现数据筛选,通过设置row隐藏功能,只显示匹配搜索条件的项,其他不匹配的项则被隐藏。关键在于使用setRowHidden方法配合indexFromItem方法,后者需要自定义QTreeWidget类并将其设为public。通过这些技术,可以在QTreeWidget中实现高效的数据筛选和显示效果。
摘要由CSDN通过智能技术生成

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

搜索框未输入
搜索数据,只显示匹配项
通过查询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对象无法直接调用,我们必须

  • 2
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
您可以在QTreeWidget的customContextMenuRequested信号中获取右键点击的位置,然后根据该位置隐藏您想要隐藏的部分菜单。 以下是示例代码: ```python from PyQt5.QtWidgets import QMenu, QAction, QTreeWidget, QTreeWidgetItem, QApplication class MyTreeWidget(QTreeWidget): def __init__(self, parent=None): super(MyTreeWidget, self).__init__(parent) self.initUI() def initUI(self): # 添加示例节点 root = QTreeWidgetItem(self) root.setText(0, "Root") child1 = QTreeWidgetItem(root) child1.setText(0, "Child1") child2 = QTreeWidgetItem(root) child2.setText(0, "Child2") # 添加右键菜单 self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.showContextMenu) self.menu = QMenu(self) self.action1 = QAction("Action1", self) self.menu.addAction(self.action1) self.action2 = QAction("Action2", self) self.menu.addAction(self.action2) self.action3 = QAction("Action3", self) self.menu.addAction(self.action3) def showContextMenu(self, pos): # 获取右键点击的节点 item = self.itemAt(pos) if not item: return # 隐藏部分菜单 if item.text(0) == "Child1": self.action2.setVisible(False) else: self.action2.setVisible(True) # 显示菜单 self.menu.exec_(self.mapToGlobal(pos)) if __name__ == '__main__': import sys app = QApplication(sys.argv) tree = MyTreeWidget() tree.show() sys.exit(app.exec_()) ``` 在此示例中,当右键点击“Child1”节点时,将隐藏“Action2”菜单,而右键点击“Root”或“Child2”节点时,将显示所有菜单。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值