How qml call static method from c++

烂漫一生 提交于 2021-01-19 22:47:55

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/45406922/how-qml-call-static-method-from-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!