asd
asd

Reputation: 266

QT c++ QSplitter saveState and restoreState

I have a splitter and I want to save his state in file with JSON.

QJsonObject mainJson;
// here I have to convert QByteArray to QString
mainJson.insert("test", QTextCodec::codecForMib(1015)->toUnicode(ui->splitter->saveState()));

QFile file("test.json");
QTextStream textStream;
file.open(QFile::WriteOnly);
textStream.setDevice(&file);
textStream.setCodec("UTF-8");
textStream << QString(QJsonDocument(mainJson).toJson()).toUtf8();
textStream.flush();
file.close();

But file contains this:

\u0000＀\u0000Ā\u0000Ȁ\u0000Ⰱ\u0000쐀\u0000\u0000Ā\u0000Ȁ

Is that ok? And how to convert this back to QByteArray for ui->splitter->restoreState(...);? PS: I use code from here

Upvotes: 2

Views: 1201

Answers (1)

eyllanesc
eyllanesc

Reputation: 244162

The logic in general is to convert the QByteArray to QString, in this case I prefer to convert it to base64 than to use a codec for unicode to avoid the problems of compression and decompression.

Considering the above, the solution is:

Save:

QJsonObject mainJson;
QByteArray state = spliter->saveState();
mainJson.insert("splitter", QJsonValue(QString::fromUtf8(state.toBase64())));
QFile file("settings.json");
if(file.open(QIODevice::WriteOnly)){
    file.write(QJsonDocument(mainJson).toJson());
    file.close();
}

Restore:

QJsonDocument doc;
QFile file("settings.json");
if(file.open(QIODevice::ReadOnly)){
    doc = QJsonDocument::fromJson(file.readAll());
    file.close();
}
if(doc.isObject()){
    QJsonObject obj = doc.object();
    QByteArray state = QByteArray::fromBase64(obj.value("splitter").toString().toUtf8());
    spliter->restoreState(state);
}

Upvotes: 2

Related Questions