Search code examples
c++qtqmlqjsengine

Register custom type in Qt with QJsEngine


I have a custom class named LObject, with a method "test" i want to call.I have a method registered in a QJSEngine that returns an instance of LObject. I get the error message when executing the method :

"Error: Unknown method return type: LObject"

I tried to register my type with Q_DECLARE_METATYPE, but then i can't call the method of my LObject.

What's the way to do it ?

Edit : A Minimal example with 3 files

server.h :

#ifndef SERVER_H
#define SERVER_H
#include <QObject>
#include <QString>
#include <QQmlEngine>
#include <QQuickView>
#include <QQmlContext>
#include <qqml.h>



class TObject : public QObject
{
    Q_OBJECT
    QML_ELEMENT
public :
    TObject(QObject * parent = nullptr, const QString & data = "") : QObject(parent) ,m_data(data){}
    TObject(const TObject & other) : QObject() ,m_data(other.m_data) {}
    ~TObject(){};
    TObject& operator=(const TObject & other) { m_data = other.m_data;return *this;}
    Q_INVOKABLE QString getData() { return m_data;}
    Q_INVOKABLE void setData(const QString & data) {m_data = data;}
private :
    QString m_data;
};


class Server : public QObject
{
    Q_OBJECT
public :

    QQmlEngine * newEngine()
    {
        QQmlEngine * ret = new QQmlEngine(this);
        ret->rootContext()->setContextProperty("Server",this);
        return ret;
    }
    Q_INVOKABLE TObject newTObject() { return TObject();}
};

Q_DECLARE_METATYPE(TObject)
#endif // SERVER_H

main.cpp :

#include "server.h"
#include <QApplication>

int main(int argc, char *argv[])

{
    QApplication a(argc, argv);

    Server s;
    QQmlEngine * e = s.newEngine();

    QQuickView view(e,nullptr);
    view.setSource(QUrl("test.qml"));
    view.show();

    return a.exec();
}

test.qml

import QtQuick 2.9
import QtQuick.Window 2.9

Text 
{
    function test()
    {
        let t = Server.newTObject() //test.qml:8: Error: Unknown method return type: TObject
        t.setData("TEST")
        return t.getData()
    }

    text : test();
}

Solution

  • Solved !

    qmlRegisterInterface<TObject>("TObject",1);
    

    and then the methods have to return a TObject*.