Using QMetaType to get the QMetaObject instance for a private, forward declared class?



  • I have two QObject derived classes, one of which is public and one which is private. The private one contains platform specific code and I'm sequestering it to its source file using the Pimpl idiom. I'd like to use both of these classes with Qt's property system and meta type system, so that I can both have properties on other classes that are pointers to these classes and so that I can access their QMetaObjects via QMetaType.

    So basically, my header file looks like this:

    class MyClass_p;
    
    class MyClass : public QObject
    {
    	Q_OBJECT
    public:
    	Q_INVOKABLE MyClass(QObject *parent = NULL);
    	...
    	MyClass_p *impl;
    	Q_PROPERTY(MyClass_p *impl MEMBER impl)
    };
    
    Q_DECLARE_OPAQUE_POINTER(MyClass_p*);
    Q_DECLARE_METATYPE(MyClass_p*);
    

    And my source file looks like this:

    class MyClass_p : public QObject {
    	Q_OBJECT
    public:
    	Q_INVOKABLE MyClass_p(QObject *parent = NULL);
    	...
    };
    
    // implementation of MyClass's and MyClass_p's methods go here
    
    #include "MyClass.moc"
    

    When I access the QMetaObject for MyClass like this:

    QMetaType(QMetaType::type("MyClass*")).metaObject();
    

    ...it works and I get the correct QMetaClass instance. But when I do the same thing for MyClass_p...

    QMetaType(QMetaType::type("MyClass_p*")).metaObject();
    

    I get NULL, as though it's not a class that's derived from QObject. But it is.

    I've tried calling qRegisterMetaType< MyClass_p*>() shortly after the application starts, but I still get NULL when I try to retrieve its QMetaObject.

    Can anyone help me figure out what I'm doing wrong? Is it even possible to use the QMetaType / QMetaObject system with a private class?


  • Qt Champions 2016

    hi
    do you have
    class MyClass_p : public QObject
    in the cpp only?
    moc.exe is only run on .h files as far as I know so it would not see it.


  • Moderators

    If it's a private implementation of a QObject then it really shouldn't be a QObject itself.
    If the class is to be used by other classes it should not really be private. It kinda defeats the purpose of being private.



  • @mrjj I believe you are correct. I found out that the problem is my use of Q_DECLARE_OPAQUE_POINTER. It apparently prevents the meta type from registering as being derived from a QObject, which makes sense since at that point there's no way for Qt to know what the class is.

    I refactored my code so that MyClass_p is no longer private or forward declared, and it fixed the issue.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.