> On 14 Apr 2023, at 23:11, Thomas Sevaldrud <tho...@silentwings.no> wrote:
> 
> Hi, in my code I have a hierarchical QMultiMap of QVariants, where a map 
> value can be a new multimap of variants. This does not compile anymore in Qt 
> 6. I.e. something like this:
> 
>       QMultiMap<QString, QVariant> varMap;
>       QMultiMap<QString, QVariant> subMap;
>       varMap.insert("key", subMap); // Compile error here, since there is no 
> conversion to QVariant
> 
> This worked in 5.15, but not in 6.5
> 
> If I change it to QMap it works, but I need multimap for this. Is this change 
> by design, or is it an omission? Any ideas for a workaround?
> 
> Cheers,
> Thomas


In Qt 5, QMultiMap was a subclass of QMap, so implicitly constructing a 
QVariant from a QMultiMap was possible because it was possible from a QMap. 
That happened to work because QMultiMap just added API on top of a QMap, and 
QMap’s data structure could handle multiple values for the same key. So no 
slicing occurred. However, if you run:

#include <QtCore>

int main(int argc, char *argv[])
{
    QMultiMap<QString, QVariant> varMap;
    QMultiMap<QString, QVariant> subMap;
    varMap.insert("key", subMap);
    qDebug() << varMap.value("key").typeName();

    return 0;
}

then you would get QVariantMap (ie a QMap<QString, QVariant>), not QMultiMap. 
So modifying the value you got out of the map would not give you multi-map 
semantics.


In Qt 6, QMultiMap is not a QMap subclass anymore (and that was a design 
decision), and since it’s such a rarely used type there is also no implicit 
constructor or conversion operator, and no built-in metatype defined for 
QMultiMap.

But since QVariant can be constructed from custom types via the fromValue 
template, you can use:

varMap.insert("key", QVariant::fromValue(subMap));

and now you can’t get it out as a QVariantMap anymore, and the code above will 
print “QMultMap<QString,QVariant>”, like it should.

Volker


_______________________________________________
Interest mailing list
Interest@qt-project.org
https://lists.qt-project.org/listinfo/interest

Reply via email to