Unsolved QML can't call static member function of C++ class
-
C++ header file:
class Worker: public Object { Q_OBJECT public: explicit Worker(QObject *parent = nullptr); Q_INVOKABLE static Worker fromJsonString(const QString &jsonString); }
register Worker class type in my main.cpp:
qmlRegisterType<Worker>("com.abc", 1, 0, "Worker");
qml file:
import com.abc 1.0 var worker = Worker. fromJsonString(jsonString)
when I run the program, output following error message:
TypeError: Property 'fromJsonString' of object [object Object] is not a function
what wrong with my code?
-
@Jazzy You miss to add
Q_OBJECT
and to declarefromJsonString()
as public::class Worker: public Object { Q_OBJECT public: explicit Worker(QObject *parent = nullptr); Q_INVOKABLE static Worker fromJsonString(const QString &jsonString); }
-
You need an instance of an object to call a function in QML, so a static function doesn't make a lot of sense in QML.
In your case you might want a singleton type acting as a Worker factory.
-
@KroMignon whether I am wrong, it is said that your cold in the same with his, both have symbol Q_OBJECT.