QML can't call static member function of C++ class
Unsolved
QML and Qt Quick
-
wrote on 22 Nov 2019, 03:57 last edited by Jazzy
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?
-
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?
wrote on 22 Nov 2019, 06:47 last edited by@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.
-
@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); }
wrote on 23 Nov 2019, 03:34 last edited by@KroMignon whether I am wrong, it is said that your cold in the same with his, both have symbol Q_OBJECT.
1/4