Search code examples
c++qtpimpl-idiom

Pimpl idiom with Qt


I am trying to build a shared library with Qt 5.6.0 and i would like to use Pimpl.

I have one class to export and this class inherits from QGraphicsScene, which itself inherits from QObject :

// CustomScene.h
#include "customscene_global.h" // recommended header from Qt
#include <QGraphicsScene> // do not compile if not present 

// forward declarations
class CustomSceneImpl;
template <typename T> class QList;
class QString;
template <class Key, class T> class QMap;
// some other classes ...

class CustomScene : public QGraphicsScene
{
  Q_OBJECT

  public :
  // some public functions

  signals:
  // some custom signals

  public slots:
  // some custom public slots

  private:
    CustomSceneImpl *m_pimpl; // pointer to private members

};

Everything's is fine if i #include <QGraphicsScene> in this header but i would prefer to forward declare QGraphicsScene. However i get the following compile error if i do that :

error: invalid use of incomplete type 'struct QGraphicsScene'

I guess i am doing something wrong with the QObject Macro, that is not recognized, and with the moc in general.

I know there are dedicated Qt Macro to use Pimpl ( Q_D, .. ) but i did not really understand how to use them and if it would fix this issue.

Thanks for your help.


Solution

  • Everything's is fine if i #include QGraphicsScene in this header but i would prefer to forward declare QGraphicsScene.

    you cannot do it as you inherit from QGraphicsScene:

    class CustomScene : public QGraphicsScene
    

    btw. this error has nothing to do with the way you implemented PIMPL idiom (actually it looks fine), inheritance from incomplete type is simply not possible as compiler needs to know the size / layout of your base class.