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

时间:2017-07-31 03:09:09

标签: c++11 qml qt5.6

我做了什么:

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:对象[object Object]的属性'validateMobile'不是函数

那么,我怎样才能正确地将静态方法暴露给qml?

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

2 个答案:

答案 0 :(得分:5)

qmlRegisterUncreatableType()完全是另一回事。

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

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

答案 1 :(得分:3)

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

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,但我没有测试过。