Cannot call C++ method when object is created in another QML module
-
Hi,
I have this QObject class:class CHPCppInterface : public QObject { Q_OBJECT QML_ELEMENT public: explicit CHPCppInterface(QObject *parent = nullptr); //int tescik; const; Q_INVOKABLE bool saveAccessToken(QString token) const; Q_INVOKABLE QString getAccessgetToken() const; signals: void tescikUpdated(); };
When I declare this class in main Window then it works:
Window { id: mainWindow width: 640 height: 480 CHPCppInterface { id: test } ........ RoundButton { onClicked: { test.saveAccessToken("test"); } }
I like to have main data module where I have common and often used thinks. So I made
DataModule.qml
and moved this class:import QtQuick Item { id: dataModule CHPCppInterface { id: test } }
And now when I try to call it:
RoundButton { onClicked: { DataModule.test.saveAccessToken("test"); } }
... I'm getting
TypeError: Cannot call method 'saveAccessToken' of undefined
How to solve that?Another annoying things:
- Even in working scenario, Qt Creator is showing red circle on that class with info "unknown component". How to fix that?
- Why in module I have to declare this class in Item{} ? Why I can't declare it directly like this:
import QtQuick CHPCppInterface { id: test }
I'm getting syntax error
-
have you tried to use QML_SINGLETON and to create the class from C++ ?
https://t1p.de/ekkeQML_SINGLETONor if you want to control the lifecycle from QML use QT_QML_SINGLETON_TYPE
https://doc.qt.io/qt-6/qml-singleton.html -
I knew both of your solutions but I thought that it is possible to fix that with QML_ELEMENT
@ekkescorner QML_SINGLETON was to much effort for me since I'm not experienced with C++ macros described on your site. Even Qt doc about QML_ELEMENT is too much complicated with my experience and I think whole idea is form over substance for my simple object
@Ronel_qtmaster I decided for this solution, works fine so far and "uknown component" marker disappeared from my QML file.Thank you both guys
-
-