- 这段代码的主要思路是读取 JSON 文件,构建树形结构,并使用 QFileSystemWatcher 监视文件变化。当文件发生变化时,重新读取 JSON 文件并更新树形结构。这使得用户可以在外部修改 JSON 文件并实时看到更新的树形结构。
#include <QApplication>
#include <QTreeView>
#include <QStandardItemModel>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonValue>
#include <QFile>
#include <QFileSystemWatcher>
#include <QDebug>
void addJsonToTree(QStandardItem* parentItem, const QJsonObject& jsonObject, const QJsonObject& jsonObjectall) {
QString layoutType = jsonObject["layout"].toString();
QJsonArray components = jsonObject["components"].toArray();
parentItem->setText(layoutType);
for (const QJsonValue& componentValue : components) {
if (componentValue.isString()) {
QString componentName = componentValue.toString();
QStandardItem* item = nullptr;
if (jsonObjectall.contains(componentName) && jsonObjectall[componentName].isObject()) {
item = new QStandardItem();
addJsonToTree(item, jsonObjectall[componentName].toObject(), jsonObjectall);
} else {
item = new QStandardItem(componentName);
}
parentItem->appendRow(item);
}
}
}
void updateTreeView(QStandardItemModel* model, const QString& filePath) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "无法打开文件: " << file.errorString();
return;
}
QByteArray jsonData = file.readAll();
file.close();
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
if (jsonDocument.isNull()) {
qDebug() << "无法解析JSON数据";
return;
}
QJsonObject jsonObject = jsonDocument.object();
model->clear();
QStandardItem* rootItem = new QStandardItem();
addJsonToTree(rootItem, jsonObject["whole"].toObject(), jsonObject);
model->appendRow(rootItem);
}
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QString filePath = "./Tree.json";
QTreeView treeView;
treeView.setHeaderHidden(true);
QStandardItemModel model;
treeView.setModel(&model);
updateTreeView(&model, filePath);
QFileSystemWatcher watcher;
watcher.addPath(filePath);
QObject::connect(&watcher, &QFileSystemWatcher::fileChanged, [&model, &filePath]() {
updateTreeView(&model, filePath);
});
treeView.show();
return app.exec();
}