nikolakoco
nikolakoco

Reputation: 1403

Get a c++ object in QML and use it in javascript

I'm making an application in which I'd like to call a function from QML in C++ source, and that c++ function to return me and object which I can use it with the same properties in the javascript part of QML. I've made the connection and everything. I've tried to send a QVariantMap and tried to use that object in javascript, but I don't get the properties of that object

Upvotes: 2

Views: 3789

Answers (3)

Pavel Osipov
Pavel Osipov

Reputation: 2097

There are two ways for exporting QObject based types from C++ to QML:

  1. Return standalone QObject directly from property READer or Q_INVOKABLE function. Note, object returned as a property has C++ ownership, Q_INVOKABLE-object has JS ownership. You can change this default behaviour via http://doc.qt.nokia.com/4.7/qdeclarativeengine.html#setObjectOwnership.
  2. Return array of QObjects. In that case you should use QObjectList, QDeclarativePropertyMap (not QVariantMap) or QAbstractListModel.

Upvotes: 3

blakharaz
blakharaz

Reputation: 2590

Your classes to be exposed have to inherit from QObject (or QDeclarativeItem if they are UI components) and you will have to register their types in your main() or in a Qt plugin before loading the QML code.

Have a look at http://developer.qt.nokia.com/doc/qt-4.7/declarative-tutorials-extending-chapter1-basics.html

Upvotes: 1

JaakkoK
JaakkoK

Reputation: 8387

To pass an object from C++ to QML as a function return value, the return value type needs to be QVariant, not QVariantMap, even though that is the type in the C++ code. So just change your initialize function signature to

QVariant initialize();

without changing anything else, and then you can access the properties.

Regarding your later comment on wanting to call methods on that returned object, that is not possible; the returned object is just a set of name-value pairs. If you want the object to have, say, an id property, you need to insert a value with that key to the QVariantMap in C++ before returning it.

Upvotes: 0

Related Questions