Home > Mobile >  Qt: Import Qml Module in imported Javascript resource
Qt: Import Qml Module in imported Javascript resource

Time:09-27

I like to access a registered QObject from within an imported js resource (qml -> .js -> Module). Access from QML works, but using ".import" as explained in the docs from within the js file does not. Some related issues raise the impression it may work (another) or not.

Is it generally possible and how, only possible for certain modules, or not at all?

Code with the annotated output of the console outputs:

main.cpp

[...]
qmlRegisterSingletonInstance<MyModule>("org.example.MyModule", 1, 0, "MyModule", (new MyModule()));
[...]

MyModule.hpp

#pragma once
#include <QObject>
class MyModule : public QObject
{
    Q_OBJECT
public:
    enum SOMETHING { AAA, BBB, CCC, DDD, EEE, FFF };
    Q_ENUM(SOMETHING)
};

main.qml

import org.example.MyModule 1.0
import "qrc:/something.js" as Something
[...]
console.log(MyModule, MyModule.DDD)// prints something like: "MyModule(0x....) 3"
[...]
Something.doit()
[...]

something.js

.import org.example.MyModule 1.0 as MyModule
[...]
console.log(MyModule, MyModule.DDD) // prints something like: "[object Object] undefined"
[...]

CodePudding user response:

Got an answer from support: Apparently, you need to prefix the Module with the import namespace, i.e. MyModule.MyModule.DDD instead of MyModule.DDD:

.import org.example.MyModule 1.0 as MyModule
[...]
console.log(MyModule.MyModule, MyModule.MyModule.DDD)
[...]
  • Related