1、介绍
树形组件
2、类和初始化
class QTreeWidget(QTreeView):
""" QTreeWidget(parent: QWidget = None) """
def __init__(self, parent=None):
pass
3、属性
4、方法
(1)setColumnCount
- 设置列数,参数为int类型。树形组件只能是设置为1
(2)setHeaderLabels
- 设置树形组件的标题,参数为str类型。不参与树的收容
(3)setColumnWidth
- 设置列宽
- 第一个参数为列的数值索引,从0开始
- 第二个参数为列宽
(4)addTopLevelItem
- 添加顶级的项,参数类型为QTreeWidgetItem
(5)expandAll
- 将全部项及子项展开
5、事件
6、示例
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QRadioButton, QCheckBox, QDialogButtonBox, \
QComboBox, QFontComboBox, QLineEdit, QTextEdit, QPlainTextEdit, QSpinBox, QTreeWidget, QTreeWidgetItem
from PyQt5.uic import loadUi
"""
极简的窗口
"""
class my_window:
def __init__(self):
self.ui = loadUi('ui\\11_QTreeWidget.ui')
self.ui: QMainWindow
self.ui.treeWidget: QTreeWidget
self.ui.pushButton: QPushButton
self.ui.pushButton.clicked.connect(self.opt)
self.ui.show()
def opt(self):
print("abc")
self.ui.treeWidget: QTreeWidget
self.myTree = self.ui.treeWidget
# 设置列数
self.myTree.setColumnCount(1)
# 设置树形控件头部的标题
self.myTree.setHeaderLabels(['机构列表'])
# 设置根节点
self.root = QTreeWidgetItem(self.myTree)
self.root.setText(0, '本单位')
# 设置树形控件的列的宽度
self.myTree.setColumnWidth(0, 100)
# 设置子节点1
child1 = QTreeWidgetItem(self.root)
child1.setText(0, '市场部')
self.root.addChild(child1)
# 设置子节点11
child11 = QTreeWidgetItem(child1)
child11.setText(0, '销售班')
# 设置子节点2
child2 = QTreeWidgetItem(self.root)
child2.setText(0, '财务部')
# 设置子节点21
child21 = QTreeWidgetItem(child2)
child21.setText(0, '财务一班')
# 加载根节点的所有属性与子控件
self.myTree.addTopLevelItem(self.root)
# TODO 优化2 给节点添加响应事件
self.myTree.clicked.connect(self.onClicked)
# 节点全部展开
self.myTree.expandAll()
def onClicked(self):
item = self.myTree.currentItem()
print('Key=%s' % (item.text(0)))
if __name__ == "__main__":
app = QApplication([])
w = my_window()
sys.exit(app.exec_())
标签:__,myTree,self,pyqt5,QTreeWidgetItem,ui,QTreeWidget
From: https://www.cnblogs.com/wd404/p/17324476.html