数据源和显示效果
思路
自定义一个容器:
QHash<int, QTreeWidgetItem *> *map = new QHash<int, QTreeWidgetItem *>;
key是节点的id
value是节点本身
先从数据库中按pid升序查询,遍历他.
如果pid为0,设置他的父节点为ui->treeWidget,后存入QHash容器
如果是其他,暂时不设置父节点,后存入QHash容器
数据库指针回到第一个,再遍历一次.
如果pid为0,不做处理.
使用id在QHash容器中返回节点本身.
使用pid在QHash容器中返回父节点.
父节点添加当前节点为子节点即可.
代码
#include "dialog.h"
#include <QDateTime>
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
QDateTime startTime = QDateTime::currentDateTime(); //开始计时
ui->treeWidget->setHeaderLabel("单位全称");
this->db = QSqlDatabase::addDatabase("QSQLITE");
this->db.setDatabaseName("data.db");
if (!db.open()) {
// 连接失败的处理逻辑
qDebug() << "连接失败";
return;
}
QSqlQuery query;
int id;
int pid;
QString name;
QHash<int, QTreeWidgetItem *> *map = new QHash<int, QTreeWidgetItem *>;
query.exec("SELECT * FROM dw_name ORDER BY pid;");
while (query.next()) {
id = query.value("id").toInt();
pid = query.value("pid").toInt();
name = query.value("name").toString();
if (pid == 0) {
QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget, QStringList() << name);
map->insert(id, item);
} else {
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << name);
map->insert(id, item);
}
}
query.first();
while (query.next()) {
id = query.value("id").toInt();
pid = query.value("pid").toInt();
name = query.value("name").toString();
if (pid == 0) {
} else {
QTreeWidgetItem *child_item = map->value(id);
QTreeWidgetItem *p_item = map->value(pid);
p_item->addChild(child_item);
}
}
QDateTime endTime = QDateTime::currentDateTime(); //结束计时
qint64 elapsedMilliseconds = endTime.toMSecsSinceEpoch() - startTime.toMSecsSinceEpoch();
QTime elapsedTime = QTime(0, 0, 0, elapsedMilliseconds);
qDebug() << "Elapsed time:" << elapsedTime.toString("mm:ss.zzz");
ui->treeWidget->expandAll();
}
Dialog::~Dialog()
{
delete ui;
}
注意事项
数据库中按pid升序查询,一定要注意,一些节点因为pid数值大,可能会排在后面,所以这里一定不能按pid升序查询的结果,同时设置顶层节点和二层以下的父节点.