Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q_OBJECT throwing 'undefined reference to vtable' error [duplicate]

I'm using Qt Creator 2.0.1 with Qt 4.7.0 (32 bit) on Windows 7 Ultimate 32 bit.

Consider the following code, which is a minimum to produce the error:

class T : public QObject, public QGraphicsItem {     Q_OBJECT  public:     T() {}      QRectF      boundingRect() const {return QRectF();}     void        paint(QPainter *painter, const QStyleOptionGraphicsItem *option,                       QWidget *widget) {} };  int main() {     T t;     return 0; } 

The above code fragment causes the following linker errors:

In function `T':

undefined reference to `vtable for T'

undefined reference to `vtable for T'

In function `~T':

undefined reference to `vtable for T'

undefined reference to `vtable for T'

If I comment out the line that contains Q_OBJECT, it compiles fine. I need signal and slots with QGraphicsItem so I need Q_OBJECT.

What is wrong with the code? Thanks.

like image 435
Donotalo Avatar asked Jan 23 '11 14:01

Donotalo


2 Answers

It is because the unit generated by MOC isn't included in the linking process. Or maybe it isn't generated at all. The first thing I'd do is to put the class declaration in a separate header file, perhaps the build system isn't scanning implementation files.

Another possibility is that the class in question once didn't belong to Qt meta object system (that is, it had no Q_OBJECT or maybe didn't inherit from QObject at all), so qmake needs to be run again in order to create the necessary rules for MOC. The easiest way to force qmake to be run is to make some insignificant changes to the project file to update its timestamp, like adding and then removing some white space. Or, if you're using Qt Creator, then just select “Run qmake” from the project context menu.

like image 95
Sergei Tachenov Avatar answered Sep 19 '22 23:09

Sergei Tachenov


If you want to define a QObject subclass in a source file then you need to add the line

#include "file.moc" 

at some point after your class definition where the name of the source file was file.cpp. You will need to re-run qmake of course so that the appropriate rule to run moc gets added to the Makefile.

Only when in a header file does the presence of Q_OBJECT in a class definition cause moc to be invoked. If it's a source file you need this extra line to force moc to be used.

I'm sure a similar question has been asked before but I couldn't find it.

like image 35
Troubadour Avatar answered Sep 21 '22 23:09

Troubadour