I want to create an interface for QObject class with signal/slot system.
The code below works but has a disadvantage: Interface inherits QObject and has no Q_OBJECT macro.
I want to make a pure virtual interface, so InterfaceClass shouldn't have a constructor. But in RealisationClass I cannot call QObject (error: type 'QObject' is not a direct base of 'RealisationClass') nor InterfaceClass (It hasn't constructor InterfaceClass(QObject* parent)) constructors. Moreover I cannot add Q_OBJECT macro in InterfaceClass (error: undefined reference to 'vtable' for InterfaceClass')
So, how should I change classes to add QObject() constructor in RealisationClass and add Q_OBJECT macro (or remove QObject inheritance) to InterfaceClass.
IntefaceClass.h:
#ifndef INTERFACE_CLASS_H
#define INTERFACE_CLASS_H
#include <QObject>
class InterfaceClass : public QObject {
Q_OBJECT
public:
virtual ~InterfaceClass(){};
virtual void foo() = 0;
};
Q_DECLARE_INTERFACE(InterfaceClass, "Interface")
#endif // INTERFACE_CLASS_H
RealisationClass.h:
#include <QObject>
#include <QDebug>
#include "InterfaceClass.h"
class RealisationClass : public InterfaceClass {
Q_OBJECT
Q_INTERFACES(InterfaceClass)
public:
explicit RealisationClass(QObject* parent = nullptr){};
void foo() override {qDebug() << "Hello, world";};
};
main.cpp:
#include <QCoreApplication>
#include "RealisationClass.h"
#include "InterfaceClass.h"
#include <QObject>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTimer everySecondTimer;
everySecondTimer.setInterval(1000);
QScopedPointer<InterfaceClass> interfacePointer(new RealisationClass);
QObject::connect(&everySecondTimer, &QTimer::timeout, interfacePointer.get(), &InterfaceClass::foo);
everySecondTimer.start();
return a.exec();
}
Edit
Q_OBJECT macro problem has another reason: I don't add InterfaceClass.h as target to Cmake's AUTOMOC (qmake (moc) didn't handle this file).
qmakebefore building. Also, you don't need to use Q_OBJECT macro in theRealisationClass- AllocesRealisationClasswithauto *r = new RealisationClass(myQObject)without any problem. And about Q_OBJECT - this is recommended when you inherit from the QObject class, but you inherit from the QObject inheritor class. For this case, I think, the most appropriate solution would be not inherit yourInterfaceClassfrom QObject. - AllocesInterfaceClassneed to be aQObject? What ifRealisationClassused multiple inheritance to derive from bothInterfaceClassandQObject? - JarMan