123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- #include "infotree_wgt.h"
- #include "ui_infotree_wgt.h"
- #include <QVBoxLayout>
- #include <QTreeView>
- #include <QStandardItemModel>
- #include <QJsonDocument>
- #include <QJsonObject>
- #include <QJsonArray>
- #include <QFile>
- #include <QStandardItem>
- #include <QMessageBox>
- #include "basedisplay_wgt.h"
- #include <QString>
- InfoTree_wgt::InfoTree_wgt(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::InfoTree_wgt),
- treeView(new QTreeView(this)), // 声明 QTreeView 为类成员
- model(new QStandardItemModel(this)) // 声明模型为类成员
- {
- ui->setupUi(this);
- // 读取 JSON 文件
- QFile file("E:\\SATpro\\die-bonder-ui\\form\\data.json");
- if (!file.open(QIODevice::ReadOnly)) {
- qWarning() << "Could not open JSON file.";
- return; // 如果文件无法打开,直接返回
- }
- QByteArray jsonData = file.readAll();
- file.close();
- if(jsonData.isEmpty())
- {
- //qWarning() << "1111111";
- QMessageBox::information(this,QString("提示"),QString("jsonData is empty"),QMessageBox::Ok);
- }
- QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
- if(jsonDoc.isEmpty())
- {
- //qWarning() << "5555555";
- QMessageBox::information(this,QString("提示"),QString("jsonDoc is empty"),QMessageBox::Ok);
- }
- if (jsonDoc.isNull() || !jsonDoc.isObject()) {
- qWarning() << "Invalid JSON data.";
- qWarning() << jsonDoc.isNull();
- qWarning() << jsonDoc.isObject();
- return; // 如果数据无效,直接返回
- }
- // 将 JSON 数据转换为树结构
- QJsonObject jsonObject = jsonDoc.object();
- QStandardItem* rootItem = createTreeFromJson(jsonObject);
- model->setItem(0, rootItem); // 从指针调用 setItem
- // 将模型设置到 QTreeView
- treeView->setModel(model); // 从指针调用 setModel
- treeView->setHeaderHidden(true); // 隐藏表头
- treeView->setWindowTitle("JSON Tree Viewer"); // 这行不太适合这里
- treeView->resize(400, 300); // 这行不太适合这里
- // 创建垂直布局并将 QTreeView 添加到布局中
- QVBoxLayout *wgt_layout = new QVBoxLayout(this);
- wgt_layout->addWidget(treeView); // 只添加一次
- setLayout(wgt_layout); // 设置布局
- connect(treeView,&QTreeView::clicked,this,&InfoTree_wgt::show);
- }
- InfoTree_wgt::~InfoTree_wgt() {
- delete ui;
- }
- //static QString str[9] = {QString("home"),QString("production"),QString("program"),
- // QString("message"),QString("module"),QString("disposition"),
- // QString("diagnosis"),QString("system"),QString("help"),
- // };
- QStandardItem *InfoTree_wgt::createTreeFromJson(const QJsonObject &jsonObject)
- {
- QStandardItem* item = new QStandardItem(jsonObject["name"].toString());
- if (jsonObject.contains("children")) {
- QJsonArray childrenArray = jsonObject["children"].toArray();
- for (const auto& childValue : childrenArray) {
- QJsonObject childObject = childValue.toObject();
- item->appendRow(createTreeFromJson(childObject));
- }
- }
- return item;
- }
- void InfoTree_wgt::show()
- {
- BaseDisplay_wgt* showWidght = new BaseDisplay_wgt;
- showWidght->show();
- }
|