Search code examples
c++11qmlqt5.6

How qml call static method from c++


What I done:

validator.h:

class UTILSSHARED_EXPORT Validator: public QObject {
    Q_OBJECT
public:
    Validator(QObject *parent = 0);
    ~Validator();
    Q_INVOKABLE static bool validateMobile(const QString target);

};

main.cpp:

qmlRegisterUncreatableType<Validator>("CT.Utils", 1, 0, "ValidatorKit", "It just a kit");

qml:

import CT.Utils 1.0
ValidatorKit.validateMobile("112344")

But unfortunately, I got an error that said: TypeError: Property 'validateMobile' of object [object Object] is not a function

So, how can I expose static method to qml correctly?

Could anybody help me? Thanks a lot.


Solution

  • qmlRegisterUncreatableType() is about something else entirely.

    What you actually need to do is expose a Validator instance as a context property to QML, or even better, implement the validator as a singleton.

    qmlRegisterSingletonType<Validator>("CT.Utils", 1, 0, "ValidatorKit", fooThatReturnsValidatorPtr);