在Qt 5中,您可以使用QJsonObject
。一種方法是明確選擇控件來序列化:
QJsonObject MyDialog::serialize() const {
QJsonObject json;
json.insert("notebookid", ui->notebookid->toPlainText());
...
return json;
}
另一種方法是使用Qt的元數據的通用序列化程序。然後,每個命名控件的用戶屬性序列:
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;
}
您可以轉換QJsonDocument
文本如下:
QJsonDocument doc(serializeDialog(myDialog));
QString jsonText = QString::fromUtf8(doc.toJson());
不幸的是,QT 5的JSON代碼需要一堆變化的Qt 4
下編譯
我認爲JSON是不容易對付前QT 5? – sark9012
@Luke:Qt根本沒有提供json類,可以使用其他庫,如[boost propertytree](http://stackoverflow.com/questions/12394472/serializing-and-deserializing-json-with-boost)。 –
讓我們[在聊天中繼續討論](http://chat.stackoverflow.com/rooms/45417/discussion-between-luke-and-kuba-ober) – sark9012