I'm quite knew to Qt and would like to understand if there is a solution for my issue.
I would like to define in C++ a global function that should be called from the QML side. I found a solution on StackOverflow that would let me invoke the function like:
myObject.myFunction();
But I would prefer to avoid the object name like:
myFunction();
that is the same we do, for example, when we need to translate a string:
qsTr("my string");
Is it possible anyway?
The closest you can get to that is by using a singleton:
Taking the example from the documentation:
Then, in QML:
You can try to use the setContextObject method of the QQmlContext if the QQmlEngine you are using. I created a minimal Gist which demonstrates the approach.
Basically, you create a custom class deriving from QObject, say,
MyApi
:In you
main.cpp
, set an instance of this class as the context object of the engine'sQQmlContext
:In the QML code, you can now access all properties, signals, slots and
Q_INVOKABLE
methods of theMyAPI
class: