Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Q_INTERFACES macro needed for child classes?

If I have class A that implements an interface (and uses Q_INTERFACES macro), then does child class B : public A also need to use the Q_INTERFACES macro?

For example:

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?
    ...
};
like image 959
Paul Masri-Stone Avatar asked May 13 '26 12:05

Paul Masri-Stone


1 Answers

Q_INTERFACES is needed for the qobject_cast function to work correctly with the interfaces a class implements. So if you want to use this function you have to place Q_INTERFACES into your class.

Docs aren't clear on what happens with the inheritance but the implementation of the generated qt_metacast function is always calling their parent qt_metacast. So in your example, even if you don't put the Q_INTERFACES macro into the B class it should still work with the qobject_cast function because it would pass it to A to execute.

like image 184
ixSci Avatar answered May 16 '26 01:05

ixSci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!