[Qt-qml] Passing QVariant from QML to CPP

aaron.kennedy at nokia.com aaron.kennedy at nokia.com
Thu Jan 13 06:03:01 CET 2011


Hi,

On 13/01/2011, at 11:13 AM, ext James Ausmus wrote:

> Hi All-
> 
> I'm trying to make Q_INVOKABLE methods on my custom Qt class that allow 
> get/set of random custom properties by name (stored in the class as a 
> QMap<QString, QVariant>). However, when I try and call the getter from a QML 
> context, the QVariant default value arg always comes up as "invalid" (from a 
> QtCreator debugger viewpoint) - I would have thought that automatic conversion 
> *to* a QVariant in a QML->CPP transition would be available - am I just doing 
> it wrong?
> 
> Here's some (condensed) sample code:
> 
> MyObj::getCustomProp(const QString &propName, const QVariant &defaultValue = 
> QVariant())
> {
>  if (!mCustomProps.contains(propName))
>    setCustomProp(propName, defaultValue);
>  return mCustomProps.value(propName);
> }
> 
> and the QML that invokes it:
> 
> myObj.getCustomProp("MyPropName", true);
> 
> 
> This also doesn't work with any well-known type - ie I can't pass a number, a 
> string, anything, and have it show up as a valid QVariant in getCustomProp.

I think your problem is caused by the use of a default value, rather than the use of a QVariant.  The first release of QML didn't support method overloading - and Qt implements invokable methods with default parameters as method overloads.  The most recent 4.7 QML branch works fine with your test code (and I even added an autotest specifically for this case to make sure).

Cheers,

Aaron



More information about the Qt-qml mailing list