(Qt) Change value by key in QVariantMap nested in QVariantList (which is also nested in QVariantMap)

366 Views Asked by At

There is the following hierarchy: QVariantMap <- QVariantList <- QVariantMap

The problem is QVariant::toList() and QVariant::toMap() return copies, which means I can't change value in a nested QVariantMap or QVariantList.

Is there any way to solse it?

P.S. I tried QJsonObject instead (because it's easy to convert it to a QVariantMap) but faced the same problem: I could not change QJsonObject stored in QJsonArray because operator[] for QJsonObject marked as const (and it was also problematic for me to work with QJsonValue and ULongLong together, so I returned to QVariant).

Hierarchy:

QVariantMap mainTable;
QVariantList list;
QVariantMap subTable;

subTable["id"] = 0;
list << subtable;
mainTable["list"] = list;

I've got no issues with filling it but when I tried to change stored values later (in other methods) there was the problem, because I can't change subTable["id"] value like:

mainTable["list"].toList()[index].toMap()["id"] = 12;
1

There are 1 best solutions below

4
On

At first glance, I can't see other solution for your problem than this, it may be heavy...

QVariantMap mainTable;
QVariantList list;
QVariantMap subTable;

subTable["id"] = 0;
list << subTable;
mainTable["list"] = list;

qDebug() << mainTable["list"].toList()[0].toMap()["id"].toInt();

auto tempList = qvariant_cast<QVariantList>(mainTable["list"]);
auto tempSubTable = qvariant_cast<QVariantMap>(tempList[0]);
tempSubTable["id"] = 42;
tempList[0] = tempSubTable;
mainTable["list"] = tempList;

qDebug() << mainTable["list"].toList()[0].toMap()["id"].toInt();

running this code gives me

0
42