How qml call static method from c++

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);

Addition to singleton type, it is possible to create a private singleton attached properties object which contains only static functions. It is more clear with an example:

class StaticValidator;

class Validator : public QObject {
    Q_OBJECT

public:
    Validator(QObject *parent = 0);
    ~Validator();
    
    // Put implementation in a source file to prevent compile errors.
    static StaticValidator* qmlAttachedProperties(QObject *object) {
        Q_UNUSED(object);
        static StaticValidator instance;
        return &instance;
    }

    static bool validateMobile(const QString& target);
};

//Q_OBJECT does not work in inner classes.
class StaticValidator : public QObject {
    Q_OBJECT

public:
    Q_INVOKABLE inline bool validateMobile(const QString& target) const {
        return Validator::validateMobile(target);
    }

private:
    StaticValidator(QObject* parent = nullptr) : QObject(parent) {}

friend class Validator;
};

QML_DECLARE_TYPE(Validator)
QML_DECLARE_TYPEINFO(Validator, QML_HAS_ATTACHED_PROPERTIES)

Register type in main or somewhere:

qmlRegisterType<Validator>("Validator", 1, 0, "Validator");

Call function in QML:

import Validator 1.0
...
var result = Validator.validateMobile(target);

It should also work in Qt4, but I didn't test it.

Tags:

C++11

Qml

Qt5.6