Register inherited QObject's meta object to QJSEngine

143 views Asked by At

I would like to inherit the QObject class, and register the inherited class's meta object to a QJSEngine instance, so that I can call let instance = new TrialObject(); in JavaScript. Here is my code:

from PyQt6.QtQml import QJSEngine
from PyQt6.QtCore import QCoreApplication, QObject


JS = """
(function() {
    let a = new TrialObject();
    return a;
})();
"""


class AttributeHandler(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self, parent)


class Main:
    def __init__(self):

        self.jsHandler = QJSEngine()
        self.jsHandler.globalObject().setProperty("TrialObject", self.jsHandler.newQMetaObject(QObject.staticMetaObject))

        r = self.jsHandler.evaluate(JS)

        print(r.toString())


if __name__ == "__main__":
    app = QCoreApplication([])
    main = Main()
    app.exec()

When (as above), I use QObject.staticMetaObject as the TrialObject, the JavaScript runs fine, and returns the QObject back to Python. Therefore QObject is invokable and working. But when I try replacing QObject.staticMetaObject with AttributeHandler.staticMetaObject, I get the error:

TypeError: AttributeHandler has no invokable constructor

... showing that AttributeHandler is not invokable. By "invokable" I mean that JavaScript can create a new instance of the class TrialObject, which I would like to be a class that has been created in Python, and inherits QObject.

How can I register an inherited QObject's meta object to QJSEngine such that it is invokable IE a new instance can be instantiated in JavaScript?

(PyQt6, Python 3.9, Windows 10)


EDIT 1

Running AttributeHandler.staticMetaObject.constructorCount() returns 0, where-as for a normal QObject, it returns 2, so i think that the problem lies in the constructor actually being recognised by the meta object system. Q_INVOKABLE doesn't exist in PyQt, so I have tried decorating the __init__ with pyqtSlot(), but this doesn't have the deired effect either.

0

There are 0 answers