[Qt-interest] QVariant conversion problem
Sean Harmer
sean.harmer at maps-technology.com
Mon Mar 22 13:00:47 CET 2010
Hi,
On Monday 22 March 2010 11:02:31 you wrote:
> On 19 March 2010 15:50, Sean Harmer <sean.harmer at maps-technology.com> wrote:
> > > 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>();
>
> This is indeed the correct approach with the added requirement that the
> actual conversion be done via T QVariant::value() e.g.
> v.value<quint32List>()
> in my case.
>
> > 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.
>
> Right. I managed to convince myself that a QList<A> is equivalent to a
> QList<B> if there's an implicit conversion from A->B.
>
> > > 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.
>
> Well, yes, but the typedef doesn't instantiate the class, so I can't see
> what Q_DECLARE_METATYPE has to work on.
>From memory, this macro just defines a template function that returns the
metatype id for your type which internally uses qRegisterMetatype(). Since
these are template functions they can just use facilities that they expect to
be present such as a default or copy ctor. If your class does not provide them
you will get a compilation error at the point where the call is made.
However, in this particular case, I do not think that Q_DECLARE_METATYPE or
qRegisterMetaType actually use the default or copy ctors. Instead they are
used in the Qt container classes and internally within QVariant's template
functions (I think).
Cheers,
Sean
More information about the Qt-interest-old
mailing list