文章目录
- 树型控件展示数据
- 修改节点数据
- 获取所有节点的数据
Qt模组参考
QWidgets
QTreeWidget
树型控件展示数据
展示数据的同时,每个节点标注数据类型。
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):
cur_value = treeWidgetItem.text(idx)
print("cur_value:", cur_value, treeWidgetItem.type_)
# 设置节点可编辑
treeWidgetItem.setFlags(treeWidgetItem.flags() | Qt.ItemIsEditable)
# 设置编辑框的样式
# QTreeWidgetItem
修改节点数据
- 双击每个节点,实现修改数据item.setFlags(Qt.ItemIsEditable);
- 可编辑时,设置样式
在这里插入代码片
获取所有节点的数据
- 数据还原为字典;
- 数据类型还原;
在这里插入代码片