pyqt5 treewidget 右键菜单程序
时间: 2023-08-30 16:10:49 浏览: 187
如下:
```
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeWidgetItem, QMenu, QAction
class TreeWidgetDemo(QMainWindow):
def __init__(self, parent=None):
super(TreeWidgetDemo, self).__init__(parent)
self.setWindowTitle('TreeWidget 例子')
self.tree = QTreeWidget()
# 设置列数
self.tree.setColumnCount(2)
# 设置树形控件头部的标题
self.tree.setHeaderLabels(['Key', 'Value'])
# 设置根节点
self.treeRoot = QTreeWidgetItem(self.tree)
self.treeRoot.setText(0, '根节点')
self.treeRoot.setText(1, '根节点的值')
# 添加子节点1
self.treeChild1 = QTreeWidgetItem(self.treeRoot)
self.treeChild1.setText(0, '子节点1')
self.treeChild1.setText(1, '子节点1的值')
# 添加子节点2
self.treeChild2 = QTreeWidgetItem(self.treeRoot)
self.treeChild2.setText(0, '子节点2')
self.treeChild2.setText(1, '子节点2的值')
# 添加子节点2的子节点
self.treeChild2Child = QTreeWidgetItem(self.treeChild2)
self.treeChild2Child.setText(0, '子节点2的子节点')
self.treeChild2Child.setText(1, '子节点2的子节点的值')
self.tree.expandAll()
self.setCentralWidget(self.tree)
# 设置右键菜单
self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self.context_menu)
def context_menu(self, pos):
item = self.tree.itemAt(pos)
if item is None:
return
menu = QMenu()
delete_action = QAction('删除', self)
delete_action.triggered.connect(lambda: self.delete_item(item))
menu.addAction(delete_action)
menu.exec(QCursor.pos())
def delete_item(self, item):
if item == self.treeRoot:
return
parent = item.parent()
parent.removeChild(item)
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = TreeWidgetDemo()
demo.show()
sys.exit(app.exec_())
```
希望可以帮到你!
阅读全文