Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How qml call static method from c++

Tags:

c++11

qml

qt5.6

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.

like image 841
WhiteWater Avatar asked Jul 31 '17 03:07

WhiteWater


2 Answers

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);
like image 81
dtech Avatar answered Nov 11 '22 07:11

dtech


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.

like image 4
Kao Avatar answered Nov 11 '22 09:11

Kao