December 20, 2011

hungnd hungnd
Lab Rat
13 posts

Q_OBJECT in cpp file

 

Hi

I have a problem with the macro Q_OBJECT. My source code:

  1. // myclass.h
  2. #ifndef MYCLASS_H
  3. #define MYCLASS_H
  4.  
  5. #include <QObject>
  6. #include <QtCore>
  7.  
  8. class MyClassPrivate;
  9.  
  10. class MyClass : public QObject
  11. {
  12.     Q_OBJECT
  13.     Q_DECLARE_PRIVATE(MyClass)
  14. public:
  15.     explicit MyClass(QObject *parent = 0);
  16.    
  17. signals:
  18.    
  19. public slots:
  20.    
  21. private:
  22.     void* const d_ptr;
  23. };
  24.  
  25. #endif // MYCLASS_H

  1. // myclass.cpp
  2. #include "myclass.h"
  3.  
  4. class MyClassPrivate: public QObject {
  5.     Q_OBJECT
  6. public:
  7.     MyClassPrivate():QObject(NULL){}
  8. signals:
  9. public slots:
  10. };
  11.  
  12. MyClass::MyClass(QObject *parent) :
  13.     QObject(parent),
  14.     d_ptr(new MyClassPrivate())
  15. {
  16. }

when compiling, I got error “undefined reference to `vtable for MyClassPrivate’”. But if I comment the Q_OBJECT declaration inside MyClassPrivate then compilation successful. Could anyone tell me why? And what if I don’t use Q_OBJECT in MyClassPrivate?
Thanks for help!

4 replies

December 20, 2011

peppe peppe
Ant Farmer
1025 posts

You need to moc that .cpp as well. The usual trick is using a #include “myclass.moc” (or “moc_myclass.cpp”) at the end of the .cpp, then rerun qmake. May I ask why do you need a private that inherits from QObject?

 Signature 

Software Engineer
KDAB (UK) Ltd., a KDAB Group company

December 20, 2011

hungnd hungnd
Lab Rat
13 posts

Thanks for quick help peppe! It worked. I would want to use signal/slot mechanism whatever it might be unnecessary :D, but I would want to try if sometime I want to use derivations of QObject inside cpp files.

December 20, 2011

Andre Andre
Area 51 Engineer
6031 posts

What I usually do, it not moc the cpp file, but just create a myclass_p.h file.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

December 20, 2011

hungnd hungnd
Lab Rat
13 posts

yep, I used to do that

 
  ‹‹ QGLWidget inside a QScrollArea      Problem with Google Maps in QT widget ››

You must log in to post a reply. Not a member yet? Register here!