【问题标题】:Is it ok to use Qt metatype system before QApplication is created?在创建 QApplication 之前使用 Qt 元类型系统可以吗?
【发布时间】:2015-04-11 19:01:25
【问题描述】:

每当我需要在 Qt 元对象系统中注册类型时,我都会使用以下代码:

*.h 文件

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 文件

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

这样我在 main() 函数启动之前就以所有可能的方式注册了 MyType。那么问题来了

1) 整个Qt MetaObject 系统是否需要一个QCoreApplication 实例?也许我的代码很巧合?

2) 有什么好的解决方案不涉及我丑陋的拐杖(即 Clerk 类)?

【问题讨论】:

    标签: c++ qt static qapplication metaobject


    【解决方案1】:

    QCoreApplication 负责为 Qt 应用程序提供事件循环,处理应用程序的初始化和结束,以及管理应用程序和系统设置。

    当创建像QWidget 这样的项目时,你肯定应该有一个QApplication 的实例。但是在创建QCoreApplicationQApplication 的实例之前使用QMetaType 类或使用qRegisterMetaType 不会有问题。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2018-12-26
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多