I inherited a class from QObject :
class Parent: public QObject
{
Q_OBJECT
QObject* cl;
public:
Parent(QObject *parent=0):QObject(parent) {
cl = NULL;
}
QObject* getCl() const {
return cl;
}
void setCl(QObject *obj) {
cl = obj;
}
};
But when I write :
Parent ev;
I get the following error:
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Parent::metaObject(void)const " (?metaObject@Parent@@UBEPBUQMetaObject@@XZ)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void * __thiscall Parent::qt_metacast(char const *)" (?qt_metacast@Parent@@UAEPAXPBD@Z)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual int __thiscall Parent::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@Parent@@UAEHW4Call@QMetaObject@@HPAPAX@Z)
You should delete the debug
folder of your application and run it again to correct this problem.
If you're using Visual Studio, delete the line Q_OBJECT
from the header file, save the file, put Q_OBJECT
back into the header file, save the file again. This should generate the moc_*
file and should build and link correctly.
I noticed some answers are based on Visual Studio.
This answer is based on Qt Creator.
Unlike the name suggest, Rebuild Project
will not wipe out everything and build from scratch. If you recently added QObject
(and/or Q_OBJECT) to your class, you'll have to run qmake
again, e.g.
This is because, by default, qmake
only runs when you do significant changes to your solution like adding new source files or modify the .pro
file. If you make edits to an existing file, it doesn't know it needs to run qmake
.
As a fall back, to brute force Qt to build everything from scratch, delete the Debug
or Release
folder.
So the issue was I needed the Qt MOC compiler to compile my .h file. This is required for any classes that extend QObject or one of its children. The fix involed (for me) right-clicking on the header file, choosing Properties, and setting the Item Type to "Qt MOC Input", then hitting "Compile" on the header, and then adding the resulting moc_myfilename.cpp file to my project.
I added cpp/ui files to my project manually, but forgot to add the header file explicitly as header file. Now when compiling I got a similar error message as above and the moc_*.cpp file(s) were not generated in the debug (or release) directory of the build. That was not such an obvious mistake, qmake did not complain and other than the linker message I got no errors.
So if anyone encounters the same problem again (or makes the same copy & pase mistake): make sure the header files have also been added to your project file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With