分配给嵌套的QVariantMap [英] Assigning to nested QVariantMap
问题描述
#include <QtCore/QCoreApplication>
#include <QVariant>
#include <QtDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVariantMap map;
map["foo"] = QVariant(QVariantMap());
map["baz"] = "asdf";
qvariant_cast<QVariantMap>(map["foo"])["bar"] = "a";
qDebug() << qvariant_cast<QVariantMap>(map["foo"])["bar"].toString();
qDebug() << map["baz"].toString();
return a.exec();
}
我试图分配到嵌套QVariantMap中的QVariant。第一个qDebug()不输出任何内容,但第二个输出asdf如预期。如何将嵌套变量映射中的bar键赋值为?
I am trying to assign to a QVariant within a nested QVariantMap. The first qDebug() outputs nothing, but the second outputs "asdf" as expected. How would I assign the "bar" key in the nested variable map to a value?
推荐答案
问题是qvariant_cast doesn' t返回对其正在操作的QVariant的内部的引用;它返回一个副本。因此,如果您使用新的子映射覆盖顶级地图中的foo元素,代码将正常工作:
The issue is that qvariant_cast doesn't return a reference to the internals of the QVariant that it is operating on; it returns a copy. As such, if you overwrite the "foo" element in your top-level map with a new child map, the code will work properly:
#include <QtCore/QCoreApplication>
#include <QVariant>
#include <QtDebug>
int main(int argc, char** argv)
{
QCoreApplication a(argc, argv);
QVariantMap map;
map["foo"] = QVariant(QVariantMap());
map["baz"] = "asdf";
QVariantMap newMap;
newMap["bar"] = "a";
map["foo"] = QVariant(newMap);
qDebug() << qvariant_cast<QVariantMap>(map["foo"])["bar"].toString();
qDebug() << map["baz"].toString();
return a.exec();
}
大概,您想要修改现有地图而不是覆盖它。您可以通过复制现有地图,添加新数据(这将导致深度复制),然后将地图重新写入以实现这一点:
Presumably, you want to modify the existing map instead of overwritting it. You can accomplish this by copying the existing map, adding the new data (which will result in a deep copy), and then writing the map back in:
QVariantMap existingMap = qvariant_cast<QVariantMap>(map["foo"]);
existingMap["bar"] = "a";
map["foo"] = QVariant(existingMap);
如果您要考虑存储大量数据,您可以重新考虑使用QVariant 。
If you're considering storing a large amount of data, you may wish to reconsider your use of QVariant.
这篇关于分配给嵌套的QVariantMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!