正如在Qt支持Json的注释中所指出的,在下一部分中,我将向您展示一个示例,另外您应该考虑到C++提供了处理内存的自由,因此在必要时在消除内存时要考虑到这一点,在Qt的情况下,很多次都是通过亲属关系树将这一责任交给Qt。
#ifndef TOKENEDITOR_H
#define TOKENEDITOR_H
#include <QWidget>
class QTableWidget;
class TokenEditor : public QWidget
{
Q_OBJECT
public:
explicit TokenEditor(QWidget *parent = nullptr);
~TokenEditor();
private:
QTableWidget *ui_userTokens;
};
#endif // TOKENEDITOR_H
*.cpp文件
#include "tokeneditor.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QTableWidget>
#include <QVBoxLayout>
TokenEditor::TokenEditor(QWidget *parent) :
QWidget(parent),
ui_userTokens(new QTableWidget)
{
const std::string json = R"([{
"key": "SHOT",
"value": "",
"description": "Current Shot node name"
},
{
"key": "PASS",
"value": "",
"description": "Current Pass node name"
},
{
"key": "SELF",
"value": "",
"description": "Current node name"
},
{
"key": "MM",
"value": "",
"description": "Current month as integer ex: 12"
},
{
"key": "DD",
"value": "",
"description": "Current day as integer ex: 07"
}
])";
QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(json));
auto layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(ui_userTokens);
ui_userTokens->setRowCount(5);
ui_userTokens->setColumnCount(3);
ui_userTokens->setHorizontalHeaderLabels({"key", "value", "description"});
int r=0;
for(const QJsonValue & val : doc.array()){
QJsonObject obj = val.toObject();
int c=0;
for(const QString & key: obj.keys()){
auto *it = new QTableWidgetItem(obj[key].toString());
ui_userTokens->setItem(r, c, it);
c++;
}
r++;
}
}
TokenEditor::~TokenEditor()
{
}