[Interest] QMultiMap as QVariant
volker.hilsheimer at qt.io
Sat Apr 15 12:07:41 CEST 2023
> On 14 Apr 2023, at 23:11, Thomas Sevaldrud <thomas at 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?
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:
int main(int argc, char *argv)
QMultiMap<QString, QVariant> varMap;
QMultiMap<QString, QVariant> subMap;
qDebug() << varMap.value("key").typeName();
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:
and now you can’t get it out as a QVariantMap anymore, and the code above will print “QMultMap<QString,QVariant>”, like it should.
More information about the Interest