0

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"
[...]

4
  • 1
    why you use qmlRegisterSingletonInstance ? your cpp class is not singleton . Commented Sep 23, 2021 at 13:00
  • what dose it mean Import Qml Module in Javascript file your title is wrong . you import one class from c++ in qml. Commented Sep 23, 2021 at 13:06
  • @Parisa.H.R The actual implementation is, it is actually just important that it is never instantiated twice. Commented Sep 23, 2021 at 13:47
  • @Parisa.H.R Edited the title, I try to import a module (c++ QObject) from a js file that is imported in qml (qml->js->module). Importing it in the qml file itself works as expected, but in the imported js file it does not work. Commented Sep 23, 2021 at 13:50

1 Answer 1

1

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)
[...]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.