Unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Parent

后端 未结 23 2354
醉话见心
醉话见心 2020-11-30 21:33

I inherited a class from QObject :

class Parent: public QObject
{
    Q_OBJECT
    QObject* cl;

public:
    Parent(QObject *parent=0):QObject(parent) {
            


        
23条回答
  •  情话喂你
    2020-11-30 22:15

    I've encountered this problem with the use of a "private class" in Qt when employing the "PIMPL" (private implementation) programming pattern. Qt uses this model all through out their source code. I have come to really like it myself.

    This technique involves the use of a "private" forward-declared class in a public header file, which will be be used by the "public" class (i.e. it's "parent"). The parent then has a pointer to an instance of the private class as a data member.

    The "private" class is defined entirely within the cpp file for the public one. There is NO header file for the private class.

    All of the "dirty work" is done with that private class. This hides all of the implementation of your public class including every other private member typically (both data and functions).

    I highly recommend learning about the PIMPL pattern - especially if you are going ever read the internal Qt source.

    Without explaining that coding style further, here's the point as it relates to this question... To get the Q_OBJECT macro to work inside the cpp for the "private" class to be QObject which can use signals/slot etc., you needed to explicitly include the .moc to the public class inside the cpp:

    #include "MyPublicClass.moc"
    

    You can ignore any IDE warnings about this line.

    I'm not sure if it matters exactly off hand, but that inclusion I always see done AFTER the private class definition, rather than at the top of the cpp (like includes are typically placed). So, the cpp layout goes like this:

    1. "Normal" includes are defined.
    2. The private class is defined.
    3. The moc for the public class is #included.
    4. The public class implementation is defined.

提交回复
热议问题