Qtreewidget右键时隐藏部分菜单
时间: 2023-07-26 08:48:41 浏览: 85
您可以在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”节点时,将显示所有菜单。
阅读全文