[Interest] QQmlPropertyList x QList in hybrid C++/QML APIs

Alan Alpert 416365416c at gmail.com
Fri Jun 14 22:21:27 CEST 2013

On Fri, Jun 14, 2013 at 12:43 PM, Sandro Andrade <sandroandrade at kde.org> wrote:
> On Fri, Jun 14, 2013 at 3:59 PM, Alan Alpert <416365416c at gmail.com> wrote:
>> On Fri, Jun 14, 2013 at 11:49 AM, Sandro Andrade <sandroandrade at kde.org> wrote:
>>> On Fri, Jun 14, 2013 at 2:48 PM, Alan Alpert <416365416c at gmail.com> wrote:
>>>> To use types across QML/C++ you should use qmlRegisterType.
>>>> QObject-based types aren't automatically registered with QML, but
>>>> certain things may still work. element.ownedAttributes is undefined
>>>> because you haven't registered the type.
>>> Ok, I've confirm that, but it seems that properties with type QList<T *>
>>> still are handled as QVariant(QList<T *>), even if T is registered in QML.
>>> It works only if property type is QVariantList, is that right ?
>> If you register both T and the class the property is on to QML, then
>> you should be able to use QList<T*> property as a read-only list of T.
>> QQmlListProperty is only strictly necessary when the list can be
>> modified from QML.
> No success yet :) ... I have no need so far to handle those item as UML objects,
> like UmlClass { ownedOperations: [UmlOperation {}] }. I just need to access
> them via javascript at Component.onCompleted function.
> I've qml-registered all my custom types (ex: qmlRegisterType<QUmlClass>();)
> and I've set context property by running:
> _quickView->engine()->rootContext()->setContextProperty("element", umlClass);
> in Component.onCompleted:
> console.log("element.ownedAttributes:" + typeof
> element.ownedAttributes + ", " + element.ownedAttributes);
> shows:
> element.ownedAttributes:object, QVariant(QList<QUmlProperty*>)
> while if doing:
> QVariantList varList;
> foreach(QUmlProperty *property, umlClass->ownedAttributes())
>     varList << qVariantFromValue(property);
> _quickView->engine()->rootContext()->setContextProperty("properties", varList);
> javascript output now shows:
> properties: object, QUmlProperty(0x1105970,
> "name"),QUmlProperty(0x110f2e0, "age")
> and it's handled as a javascript array, as expected.
> Am I missing something ?

I can think of three things we might be missing here...

1) Are you using QtQuick 1 or QtQuick 2? QtQuick 1 JS support is
weaker, and so that could be it.
2) Are all the classes involved QObject derived classes? It certainly
won't work otherwise.
3) I could be mistaken about how well QList<QObject*> works read-only
in script snippets. If you are exclusively concerned with script, have
a look at the http://qt-project.org/doc/qt-5.0/qtqml/qjsvalue.html
QJSValue type and consider exposing the context property through that
(although if you get to the point of having a divergent script/C++
API, you might just use QQmlListProperty).

Alan Alpert

More information about the Interest mailing list