C ++ / Qt macro Q_OBJECT throws error
I have just started programming in the Qt environment. Below is a very simple program:
#include <QtCore/QCoreApplication>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass() {}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass *c = new MyClass();
return a.exec();
}
But I get the following error when I try to compile and run it:
In function MyClass
:
undefined reference to vtable for MyClass
But when I remove the QObject macro everything works fine. Note that the class is defined in the same file as the main function.
I am using Qt version 4.7, running Win 7.
What is causing this problem?
Update: I am getting the same error when I define my class in a separate header file. mytimer.h:
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QtCore>
class MyTimer : public QObject
{
Q_OBJECT
public:
QTimer *timer;
MyTimer();
public slots:
void DisplayMessage();
};
#endif // MYTIMER_H
mytimer.cpp:
#include "mytimer.h"
#include <QtCore>
MyTimer::MyTimer()
{
timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(DisplayMessage()));
timer->start(1000);
}
void MyTimer::DisplayMessage()
{
qDebug() << "timed out";
}
And this is main.cpp:
#include <QtCore/QCoreApplication>
#include <QDebug>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyTimer *mt = new MyTimer();
return a.exec();
}
source to share
You need to compile it with qmake, which will create mock methods for your custom QObject class. See here for more on generating moc files.
Since your example contains no header files, it is not parsed and no moc files are generated. You need to declare MyClass in a separate header file and run the moc generator.
source to share