How do I convert QMap<QString, QMap<QString, int> > to a QVariant?

fenix picture fenix · Jul 19, 2010 · Viewed 9k times · Source

QVariant (needed for QSettings class) supports creation from QMap<QString, QVariant>

But trying to initialise something like this:

QMap<QString, QVariant(QMap<QString, QVariant>)> i;

Gives the error:

function returning a function.

So then I tried the QMap<QString, QVariant> overload for QVariant() and got

error: no matching function for call to QVariant::QVariant(QMap<QString, QMap<QString, int> >&)

Now I tried a typecast:

QMap<QString, (QVariant)QMap<QString, QVariant> > i;

and got

template argument 2 is invalid
invalid type in declaration before ';' token

So what's the required voodoo to convert a nested QMap to a QVariant object?

Answer

Ken Bloom picture Ken Bloom · Jul 19, 2010
  1. In QMap<QString, QVariant(QMap<QString, QVariant>)>, you have defined a map from a string to a function type. What you really want is a QMap<QString, QVariant>.

  2. You don't want a QMap<QString,(QVariant)QMap<QString, QVariant> > because that's just syntactically incorrect. Both template parameters need to be type names, and typecast can't be part of at type name.

  3. Putting a QMap<QString, int> (or almost any other type of QMap) into a QVariant won't work. The only QMap type that can be converted into a QVariant is a QMap<QString,QVariant>.

    There's a typedef for this type that may be useful: QVariantMap. If you stick to using QVariantMap for this situation, then things will work properly for you.