child 类 是否需要 Q_INTERFACES 宏?

Is Q_INTERFACES macro needed for child classes?

如果我有 class A 实现接口(并使用 Q_INTERFACES 宏),那么 child class B : public A还需要使用Q_INTERFACES宏吗?

例如:

IMovable.h

#include <QObject>

class IMovable
{
public slots:
    virtual void moveLeft(int distance) = 0;
    virtual void moveRight(int distance) = 0;
    virtual void moveUp(int distance) = 0;
    virtual void moveDown(int distance) = 0;
signals:
    virtual void moved(int x, int y) = 0;
};

Q_DECLARE_INTERFACE(IMovable, "my_IMovable")

A.h

#include <QObject>
#include "IMovable.h"

class A : public QObject, public IMovable
{
    Q_OBJECT
    Q_INTERFACES(IMovable)
public:
    explicit A(QObject *parent = nullptr);
    virtual ~A();

public slots:
    //implement IMovable public slots
    void moveLeft(int distance) override;
    void moveRight(int distance) override;
    void moveUp(int distance) override;
    void moveDown(int distance) override;

signals:
    //implement IMovable signals
    void moved(int x, int y) override;
};

B.h

#include "A.h"

class B : public A
{
    Q_OBJECT
    // Do I need Q_INTERFACES(IMovable) here?
    ...
};

Q_INTERFACESqobject_cast 函数与 class 实现的接口正确工作所必需的。所以如果你想使用这个函数,你必须将 Q_INTERFACES 放入你的 class.

文档不清楚继承发生了什么,但是生成的 qt_metacast 函数的实现总是调用它们的父 qt_metacast。因此,在您的示例中,即使您没有将 Q_INTERFACES 宏放入 B class 中,它仍应与 qobject_cast 函数一起使用,因为它会将它传递给 A 执行。