How to create and use C++ objects in QML Javascript

folibis picture folibis · May 29, 2014 · Viewed 9k times · Source

My app uses both c++ and QML.

I've defined several objects in C++ part to access SQL etc.

It looks like:

class MyObject : public QObject
{
    Q_OBJECT
public:
    MyObject(QObject *parent = 0);
    Q_INVOKABLE void someFunction(const QString &query);
};

qmlRegisterType<MyObject>("xxx.xxx", 1, 0, "MyObject");

Ideally, I need to use these objects only in Javascript not in QML.

I tried a lot of examples and read all the documentation but still can't solve my problem.

So my questions:

  • How can I instance in Javascript an object defined in C++? I tried var obj = Qt.createComponent("MyObject"); but it seems not works. Is it possible to define new object in normal JS style - var obj = new MyObject;?
  • How can I access this created object in javascript? I tried obj.someFunction("xxx") but got some error - TypeError: Property 'someFunction' of object QQmlComponent(0x3605f5c0) is not a function. What I do wrong here? My object derived from QObject, not from QQmlComponent.

Answer

OliJG picture OliJG · Aug 6, 2015

Your object isn't a Component, but you can use Qt.createQmlObject instead.