How qml call static method from c++
Asked Answered
I

2

11

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.

Ixia answered 31/7, 2017 at 3:9 Comment(0)
J
6

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);
Janes answered 31/7, 2017 at 3:24 Comment(4)
There is no other way.Janes
Thanks a lot for your helping.Ixia
Sadly, that works only for QObjects. Any solution for a Q_GADGET ?Powell
I solved my issue by using a member in my application class. I had another idea of using a template class that would inherit bith my Q_GADGET and QObject, but did not go through.Powell
F
5

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.

Fallonfallout answered 17/1, 2021 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.