0

I would like to know the easiest way to implement the pimpl idiom in Qt objects. What I want to have is something like this:

pimpl.h:

class B;

class A: public QObject {
    B *b;
}

pimpl.cxx:

class B: public QObject {
}

Now, as is obvious, Qt will not pass the class B to create the moc for it. How this can be handled? I want to have the implementation of B in the .cxx explicitly.

underscore_d
  • 5,331
  • 3
  • 29
  • 56
  • Possible duplicate of [How to use the Qt's PIMPL idiom?](http://stackoverflow.com/questions/25250171/how-to-use-the-qts-pimpl-idiom) – TheDarkKnight Jul 27 '16 at 08:35
  • @TheDarkKnight As far I can see, there's no mention of the impl class itself being a `QObject` in the linked answer, so I voted to leave open. – anderas Jul 27 '16 at 14:07

2 Answers2

4

You could create a pimpl-private.h that contains the definition of B and is only included from pimpl.cxx, nowhere else. Then you can run moc over this header.

Sebastian Redl
  • 61,331
  • 8
  • 105
  • 140
  • Yes, this is fine. However, I was looking for a hack if possible to keep it in the .cxx file as I am more used to it and do not have to fwd declare/include types there for most the part. – code_not_yet_complete Jul 26 '16 at 13:42
  • @code_not_yet_complete: See https://stackoverflow.com/questions/34928933/why-is-important-to-include-moc-file-at-end-of-a-qt-source-code-file – peppe Jul 26 '16 at 14:40
2

It is possible to have the code in the .cpp file by adding

#inlude "pimpl.moc"

at the end(!) of "pimpl.cxx" and re-running qmake. This will generate a Makefiule rule to run the file through moc and put the output into a "pmipl.moc" so everything magically works.

yama
  • 81
  • 1