How to register a class in a .js file of QML using C++?
-
How to register a class in a .js file of QML using C++? For example, I have an OaiClient in C++ and want to use ‘const client = new OaiClient’ in JavaScript.
I checked the documentation, which states: You cannot use the globalObject() function to change the global object of a QQmlEngine.
What should I do? -
Good morning and welcome to the Qt Forum,
how have you written your C++ extension?
If you follow this documentation, it will be accessible from QML and Javascript. -
Good morning and welcome to the Qt Forum,
how have you written your C++ extension?
If you follow this documentation, it will be accessible from QML and Javascript.@Axel-Spoerl Thank you for your reply. I have read this document. What I want to do is something similar to the following:
import QtQuick import "backend.js" as Backend Item { Component.onCompleted: { Backend.func() } }// backend.js function func() { const obj = new OaiClient() // OaiClient is a JS class registered from C++ }What I want is to be able to register a C++ class to a JS file, and the JS file can use the
newkeyword to instantiate this class. -
Good morning and welcome to the Qt Forum,
how have you written your C++ extension?
If you follow this documentation, it will be accessible from QML and Javascript.@Axel-Spoerl I found that the following code works:
QQmlApplicationEngine engine; auto ctor = engine.evaluate(R"( (function() { this.name = "test" this.create = function(){ return "hello world!" } }) )"); engine.globalObject().setProperty("OaiClient", ctor);However, I don’t understand what the documentation means when it says that the globalobject properties should not be modified, and I’m unsure what the implications of doing so might be.