qml 如何从 C++ 调用静态方法

How qml call static method from c++

我做了什么:

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

但不幸的是,我收到一条错误消息:TypeError: 属性 'validateMobile' of object [object Object] is not a function

那么,如何正确地将静态方法暴露给qml呢?

有人能帮帮我吗?非常感谢。

qmlRegisterUncreatableType() 完全是另一回事。

您实际需要做的是将 Validator 实例作为上下文 属性 公开给 QML,甚至更好,implement the validator as a singleton.

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

除了单例类型之外,还可以创建仅包含静态函数的私有单例附加属性对象。举个例子更清楚:

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)

在 main 或某处注册类型:

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

在QML中调用函数:

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

在Qt4中应该也可以,但我没有测试。