我来自python和pyside的背景。因此,对于在C++中可能出现的奇怪做法,我深表歉意。
两个问题:
我的目标是最终扩展QTableWidget的子类,以添加用于从文件加载并保存到文件的方法。类似于预设。
词典列表:
[
{
"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",
}
]
cpp
#include "tokeneditor.h"
#include <QTableWidget>
#include <QVBoxLayout>
TokenEditor::TokenEditor(QWidget *parent) : QWidget(parent)
{
// Controls
QTableWidget *ui_userTokens = new QTableWidget();
// Layout
QVBoxLayout * layout = new QVBoxLayout();
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(ui_userTokens);
setLayout(layout);
// populate table with data...
}
最佳答案
正如评论中提到的,Qt支持Json,在下一部分中,我将向您展示一个示例,此外,您还应考虑到C++提供了处理内存的自由,因此考虑到在有必要的情况下消除内存(对于Qt,它是很多次)是通过亲属树将责任交给Qt。
* .h
#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()
{
}