展示数据的同时,每个节点标注数据类型。
class MyWindow(QWidget):
def __init__(self, title):
super(MyWindow, self).__init__()
self.setWindowTitle(title)
self.resize(500, 300)
self.set_ui()
def set_ui(self):
# 显示图片
label = QLabel(self)
label.setText("xxxxx")
qimg = QPixmap("./bg.jpg")
qimg.scaledToHeight(120)
qimg.scaledToWidth(200)
label.setPixmap(qimg)
label.resize(200, 120)
label.move(100, 200)
# QTreeWidget
self.q_tree = QTreeWidget(self)
self.q_tree.setColumnCount(3)
self.q_tree.setHeaderLabels(["a", "b", "c"]) # 设置表头
self.q_tree.setFixedWidth(500)
self.q_tree.setFixedHeight(460)
self.q_tree.move(80, 80)
self.q_tree.itemDoubleClicked.connect(self.modify_slot)
# 选择不同的节点时的信号
# self.q_tree.currentItemChanged.connect(self.data_change_slot)
# data
data = {
"d1": {
"name": "jack",
"age": 20,
"friends": ["tom", "lucy"],
"bid": [1, 3, 6]
},
"d2": [1.4, 3.2, 6.7],
"d3": 3.14
}
# 展示数据
self.show_data(data)
def show_data(self, data):
""" 展示数据 """
for k, v in data.items():
if isinstance(v, dict):
node = QTreeWidgetItem(self.q_tree)
node.type_ = dict
node.setText(0, k)
self.show_dict(v, node)
elif isinstance(v, list):
node = QTreeWidgetItem(self.q_tree)
node.type_ = list
node.setText(0, k)
self.show_list(k, v, node)
else:
node = QTreeWidgetItem(self.q_tree)
node.type_ = type(v)
node.setText(0, k)
node.setText(1, str(v))
def show_list(self, key, data, root):
""" 展示列表 """
for idx, v in enumerate(data):
if isinstance(v, dict):
node = QTreeWidgetItem(root)
node.type_ = dict
node.setText(0, str(idx))
self.show_dict(v, node)
elif isinstance(v, list):
node = QTreeWidgetItem(root)
node.type_ = list
node.setText(0, str(idx))
self.show_list(idx, v, node)
else:
node = QTreeWidgetItem(root)
node.type_ = type(v)
node.setText(0, key + f"[{root.childCount() - 1}]")
node.setText(1, str(v))
def show_dict(self, data, root):
""" 递归展示字典 """
for k, v in data.items():
if isinstance(v, dict):
node = QTreeWidgetItem(root)
node.type_ = dict
node.setText(0, k)
self.show_dict(v, node)
elif isinstance(v, list):
node = QTreeWidgetItem(root)
node.type_ = list
node.setText(0, k)
self.show_list(k, v, node)
else:
node = QTreeWidgetItem(root)
node.type_ = type(v)
node.setText(0, k)
node.setText(1, str(v))
def data_change_slot(self, *args):
print("args:", args)
def modify_slot(self, treeWidgetItem, idx):
"""双击每一个节点,触发itemDoubleClicked信号:
1. 槽函数内部,设置QTreeWidgetItem可编辑
"""
cur_value = treeWidgetItem.text(idx)
print("cur_value:", cur_value, treeWidgetItem.type_)
# 设置节点可编辑
treeWidgetItem.setFlags(treeWidgetItem.flags() | Qt.ItemIsEditable)
# 设置编辑框(QLineEdit)的样式
# 提前设置QLineEdit控件的样式
# 双击每个节点,触发QTreeWidget.itemDoubleClicked信号
# 设置可编辑
item.setFlags(item.flags() | Qt.ItemIsEditable)
# 设置编辑框样式
# 提前设置QLineEdit控件的样式
# 遍历顶级节点,如果当前节点没有子节点,则为叶子节点;
# 否则,递归该节点,依次获取其下的数据,并转换类型
# 最后得到一个字典数据;