[Interest] Creating C++ objects in JavaScript with operator new

Jérôme Godbout godboutj at amotus.ca
Mon Apr 15 22:59:45 CEST 2019


You can expose the C++ object to metatype, then register the MetaObject using qmlRegisterType<>() to the Qml types. You then should create a Component and instanciate the component into an actual object:

I strongly suggest you read this:
https://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html

property Component myComponent: MyClass 
{
   property bool allComponentValue: otherIdBinding.visible
}

function doSomething()
{
	var myobject = allComponentValue. createObject(myparent, {});
	....
}

The QObject, need the parent and initial property (you can create binding using Qt.binding(function(){ return OtherBindingId.value; })
This should cover how to create object. You will need to destroy the object by either the parent or by destroying it manually.

You can also generate an object from Qml code directly: 
Qt.createQmlObject()

The new is lacking too much information to create the QObject properly.

-----Original Message-----
From: Interest <interest-bounces at qt-project.org> On Behalf Of Richard Weickelt
Sent: April 15, 2019 4:10 PM
To: interest at qt-project.org
Subject: [Interest] Creating C++ objects in JavaScript with operator new

Hi,

is there an easy way to register a QObject-derived class in the QML type system so that I can instantiate it from within JavaScript code using operator new?

function someJavaScriptFunction(){
    var myObject = new MyClass("blabla");
    // ...
}

Right now I am registering another class as a proxy which then registers the constructor function for my class. This looks overly verbose and clunky. Is there a simpler way?


class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject* parent = nullptr, const QString& someParam = "");

    Q_INVOKABLE bool someMethod() const;
    static void registerAsJSType(QJSEngine* engine); };

class MyClassCreator : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE MyClass* createObject(const QVariantMap& arguments); };

void MyClass::registerAsJSType(QJSEngine* engine) {
    QJSValue creator = engine->newQObject(new MyClassCreator());
    engine->globalObject().setProperty("_MyClassCreator", creator);
    engine->evaluate("function MyClass(param) { return _MyClassCreator.createObject({ someParam: param }); }"); }

MyClass* MyClassCreator::createObject(const QVariantMap& arguments) {
    QString someParam = arguments.value("someParam").toString();
    return new MyClass(qmlEngine(this), someParam); }


Thanks
Richard
_______________________________________________
Interest mailing list
Interest at qt-project.org
https://lists.qt-project.org/listinfo/interest


More information about the Interest mailing list