In Qt 5, you can use QJsonObject
. One way is to explicitly select the controls to serialize:
QJsonObject MyDialog::serialize() const {
QJsonObject json;
json.insert("notebookid", ui->notebookid->toPlainText());
...
return json;
}
Another way is to have a generic serializer that uses the Qt's metadata. Each named control's user property is then serialized:
QJsonObject serializeDialog(const QWidget * dialog) {
QJsonObject json;
foreach (QWidget * widget, dialog->findChildren<QWidget*>()) {
if (widget->objectName().isEmpty()) continue;
QMetaProperty prop = widget->metaObject()->userProperty();
if (! prop.isValid()) continue;
QJsonValue val(QJsonValue::fromVariant(prop.read(widget)));
if (val.isUndefined()) continue;
json.insert(widget->objectName(), val);
}
return json;
}
You can convert QJsonDocument
to text as follows:
QJsonDocument doc(serializeDialog(myDialog));
QString jsonText = QString::fromUtf8(doc.toJson());
Unfortunately, Qt 5's json code requires a bunch of changes to compile under Qt 4.