一个简单的treeivew,以表格方式保存比较简单,遍历所有节点,记录parentNode、node、data即可
parentid | data | id |
002 | xx2 | 001 |
005 | xx5 | 000 |
003 | xx3 | 001 |
006 | xx6 | 002 |
007 | xx7 | 001 |
000 | xx0 | 001 |
001 | xx1 | -1 |
004 | xx4 | 007 |
如何将表格转为tree数据,代码如下:
#include "mainwindow.h"
#include <QtWidgets>
struct DataInfo{
QString id;
QString name;
QString parentId;
};
struct DataNode{
DataInfo info;
QMap<QString, DataNode> child;
};
void print(QMap<QString, DataNode> map)
{
for(auto d = map.begin(); d != map.end(); d ++) {
auto k = d.value();
qDebug() << __LINE__ << d.key() << k.info.name;
print(k.child);
}
}
void fillTree(QMap<QString, DataNode> map, QStandardItem *item)
{
for(auto k = map.begin(); k != map.end(); k ++) {
DataNode d = k.value();
QStandardItem *itm = new QStandardItem;
itm->setText(d.info.name);
item->appendRow(itm);
fillTree(d.child, itm);
}
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QList<DataInfo> infoList;
infoList << DataInfo{"002", "xx2", "001"};
infoList << DataInfo{"005", "xx5", "000"};
infoList << DataInfo{"003", "xx3", "001"};
infoList << DataInfo{"006", "xx6", "002"};
infoList << DataInfo{"007", "xx7", "001"};
infoList << DataInfo{"000", "xx0", "001"};
infoList << DataInfo{"001", "xx1", "-1"};
infoList << DataInfo{"004", "xx4", "007"};
//生成树状图
QMap<QString, DataNode> dataMap;
QMap<QString, DataNode*> ptrMap;
for(auto d : infoList) {
//父节点存在 并且 子节点存在
if(ptrMap.contains(d.parentId) && ptrMap.contains(d.id)) {
ptrMap[d.id]->info = d;
ptrMap[d.parentId]->child[d.id] = dataMap.take(d.id);
ptrMap.insert(d.id, &ptrMap[d.parentId]->child[d.id]);
continue;
}
//父节点存在 并且 子节点不存在
if(ptrMap.contains(d.parentId)) {
ptrMap[d.parentId]->child[d.id].info = d;
ptrMap.insert(d.id, &ptrMap[d.parentId]->child[d.id]);
continue;
}
//父节点不存在 并且 子节点存在
if(ptrMap.contains(d.id)) {
ptrMap[d.id]->info = d;
dataMap[d.parentId].child[d.id] = dataMap.take(d.id);
ptrMap.insert(d.parentId, &dataMap[d.parentId]);
continue;
}
//父节点不存在 并且 子节点不存在
dataMap[d.parentId].child[d.id].info = d;
ptrMap.insert(d.parentId, &dataMap[d.parentId]);
ptrMap.insert(d.id, &dataMap[d.parentId].child[d.id]);
}
QTreeView view;
QStandardItemModel *model = new QStandardItemModel;
view.setModel(model);
view.header()->hide();
auto root = model->invisibleRootItem();
root->appendRow(new QStandardItem("root"));
root = root->child(0);
print(dataMap);
fillTree(dataMap, root);
view.expandAll();
view.show();
return a.exec();
}