[Interest] QJsonDocument::fromVariant failing with list

Thiago Macieira thiago.macieira at intel.com
Thu Jun 10 01:26:46 CEST 2021


On Wednesday, 9 June 2021 10:21:28 PDT Jason H wrote:
> > Stop using QVariantMapList. You want a QVariantMap.
> 
> I think you meant QVariantList?:
>  QVariantMap map {
>    {"err", QVariant()},
>    {"letters", QVariantList {
>      QVariantMap {{"a",1}},
>      QVariantMap {{"b",2}},
>      QVariantMap {{"c",3}}
>    }}
>  };

No, I had really meant QVariantMap when I wrote, but I had no way of knowing 
what *you* wanted. There's no JSON type that is a homogeneous list of maps, so 
I had to infer what you had wanted.

> I had hoped that by using QList<QVariantMap> that I could omit the 3
> QVariantMaps above.

I think that's a limitation of the initialiser list. Does it still happen with 
the CTAD deduction guides from Qt 6?

> But anyway, it seems my mistake was thinking that QVariant hold a
> QList<QVariantMap>, the best thing possible is the more general case of
> QVariantList, and this can be a heterogeneous collection of QVariants.
> Neither compiler nor Qt is capable of enforcing homogeneity as a QList of
> QVariantMaps AND having that collection being a QVariant itself, in a
> declaration. It would have to be built at runtime.
> 
> Did I get that right?

QVariant can hold any type, so long as it's declared as a metatype and 
registered (registration is automatic on first use). Your problem is that 
QJsonDocument::fromVariant doesn't know about those extra types: you can use 
QList<QVariantMap>, QVector<QVariantMap>, std::vector<QVariantMap> or anything 
else. That doesn't make the type supported by the conversion routine.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel DPG Cloud Engineering





More information about the Interest mailing list