How to properly use qRegisterMetaType on a class derived from QObject?

前端 未结 3 1584
南方客
南方客 2020-12-08 15:09

I\'ve been searching far and wide for an answer to this but to no avail. My lament is as follows:

I have a ClassA that roughly looks like this:

3条回答
  •  感情败类
    2020-12-08 15:34

    Here's an update to Chris' solution #2 for Qt 5:

    namespace QtMetaTypePrivate {
        template <>
        struct QMetaTypeFunctionHelper {
            static void Delete(void *t)
            {
                delete static_cast(t);
            }
    
            static void *Create(const void *t)
            {
                Q_UNUSED(t)
                return new ClassA();
            }
    
            static void Destruct(void *t)
            {
                Q_UNUSED(t) // Silence MSVC that warns for POD types.
                static_cast(t)->~ClassA();
            }
    
            static void *Construct(void *where, const void *t)
            {
                Q_UNUSED(t)
                return new (where) ClassA;
            }
        #ifndef QT_NO_DATASTREAM
            static void Save(QDataStream &stream, const void *t)
            {
                stream << *static_cast(t);
            }
    
            static void Load(QDataStream &stream, void *t)
            {
                stream >> *static_cast(t);
            }
        #endif // QT_NO_DATASTREAM
        };
    }
    

    If your ClassA doesn't implement operator<< and operator>> helpers for QDataStream, comment out the bodies of Save and Load or you'll still have a compiler error.

提交回复
热议问题