c++qtstaticqapplicationmetaobject

Is it ok to use Qt metatype system before QApplication is created?


I use following code whenever I need to register a type in Qt metaobject system:

*.h file

class MyClass
{

    //.....

    class MyType {.....};
    static const int metaType_MyType;

    class MetaClerk
    {
    public:
        MetaClerk(void);
    };
    static const MetaClerk metaClerk;

    //.....

};
Q_DECLARE_METATYPE(MyClass::MyType)
QDataStream &operator<<(QDataStream &stream, const MyClass::MyType &a);
QDataStream &operator>>(QDataStream &stream, MyClass::MyType &a);

*.cpp file

//.....
const int MyClass::metaType_MyType = qRegisterMetaType<MyClass::MyType>("MyClass::MyType");
MyClass::MetaClerk::MetaClerk()
{
    qRegisterMetaTypeStreamOperators<MyClass::MyType>("MyClass::MyType");
}
const MyClass::MetaClerk MyClass::metaClerk;
//.....

This way I have MyType registered in all possible ways before the main() function even starts. So, the question is

1) Does the whole Qt MetaObject system need an instance of QCoreApplication? Maybe my code works by happy coincidence?

2) Is there any nice solution NOT involving my ugly crutch (namely the Clerk class)?


Solution

  • QCoreApplication is responsible for providing an event loop for Qt applications, handling the application's initialization and finalization and managing the application and system settings.

    When creating items like QWidget you definitely should have an instance of QApplication. But there would be no trouble using the QMetaType class or using qRegisterMetaType before creating an instance of QCoreApplication or QApplication.