[Qt-interest] QVariant conversion problem

Sean Harmer sean.harmer at maps-technology.com
Fri Mar 19 16:50:22 CET 2010


Hi,

On Friday 19 March 2010 15:15:25 Stephen Collyer wrote:
> On 18 March 2010 19:56, Sean Harmer <sean.harmer at maps-technology.com> wrote:
> > You need to put your data into a QVariant first. There is no QVariant
> > constructor that takes your type, so you need something like:
> > 
> > const QList<quint32> storytranslation_ids_by_lang
> > QMap<QString, QVariant>   where_data;
> > QVariant v;
> > v.setValue(storytranslation_ids_by_lang);
> > where_data["fk_storytranslation_id"] = v;
> > 
> > Note that you also need to tell QMetaType about your new type that you
> > wish to store within QVariant too. You can do this with the
> > Q_DECLARE_METATYPE() macro.
> 
> Right, this seems like the way to go though I'm not sure of
> some details. I have satisfied the compiler by declaring:
> 
> typedef QList<quint32>          quint32List;
> Q_DECLARE_METATYPE(quint32List)
> 
> and assigning the value via QVariant::setValue() as you suggested.

OK good. Glad it is compiling at least.

> However, I seem to run into another problem later on, where I perform
> a QVariant::canConvert(QVariant::List) test on the value assigned
> using QVariant::setValue() - this returns false. Does this suggest that
> the QVariant::canConvert() is not aware of the Q_DECLARE_METATYPE
> declaration for some reason ?

It is because QVariant::List corresponds to QList<QVariant> according to the 
docs which is not the same as QList<quint32>. You need to use the template 
version of the canConvert() function e.g.:

bool b = myVariant.canConvert<quint32List>();

The QVariant knows that its internal void* pointer is pointing at an object of 
type quint32List so this call will return true.

The cause of your problems is thinking that QList<QVariant> is the same as 
QList<quint32>. Just because you can store a quint32 in a QVariant, it does 
not however make them the same because in your case the quint32's are not 
wrapped in a QVariant inside your list.

> I'm also not entirely happy with my passing the typedef to
> Q_DECLARE_METATYPE, as the somewhat scanty documentation seems
> to suggest that it needs to see a full class definition (with default and
> copy ctors,
> as well).

Your type is a full class - it is a QList - which does define copy and default 
ctors. So you are fine.

Cheers,

Sean




More information about the Qt-interest-old mailing list