我正在使用嵌套的 QVariantMap 并且在定义一个采用路径(字符串列表)并将指针返回到低级 QVariantMaps 的方法时遇到问题:
QVariantMap * getQVariantMap( QStringList spec) const {
QVariantMap * deep_p = this->hash_p;
for( QStringList::const_iterator it = spec.begin();
it!= spec.end();
++it)
{
QVariantMap::const_iterator i = hash_p->find( *it);
if( i == hash_p->end())
return 0x00;
res_p = & i.value().toMap();
}
return res_p;
}
...
QVariantMap map, level1, level2;
level2["L2"] = "bazzinga!";
level1["L1"] = QVariant::fromValue( level2);
level1["foo"] = "foo";
map["L0"] = QVariant::fromValue( level1);
map["foo"] = "foo";
QStringList qsl;
qsl.append( "L1");
qsl.append( "L0");
QVariantMap * qvm = getQVariantMap( qsl);//pointer to level2 part of the nested QVariantMap.
qvm[ "foo"] = "baz";
//map[ "L0"].toMap()[ "L1"].toMap()[ "foo"] == "baz";
...
我收到以下错误:
taking address of temporary [-fpermissive]
我知道为什么。问题是我需要获取指向嵌套结构部分的指针,但我无法获得对 QVariant 内部的引用。我尝试使用 data_ptr,在分配给嵌套 QVariantMap的帖子中建议,但没有运气。出于显而易见的原因,我不想对插入/删除/值进行特殊包装(这就是为什么,据我所知,链接主题中接受的答案不是我的情况)。
我试过了:
- 将 QPointer 存储在 QVariant 中——没有运气,因为 QVariant 不是 QObject;
- 使用 QVariant::fromValue(QVariantMap *) 存储指针,但是当我调用 toMap() 时,它返回 QVariantMap,而不是指针,所以我再次得到临时地址错误。不管怎样,我认为这不是我想要的。
有人应该如何正确地做到这一点?