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

前端 未结 3 1585
南方客
南方客 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:31

    A few things:

    • The reason that registering ClassA* isn't working is because your call to construct() is constructing a pointer to a ClassA object, but not an actual object.

    • It is worthy of noting the following quote from the QMetaType documentation:

    Any class or struct that has a public default constructor, a public copy constructor, and a public destructor can be registered.

    • Take a look at Qt's implementation of qMetaTypeConstructHelper:

      template 
      void *qMetaTypeConstructHelper(const T *t)
      {
          if (!t)
              return new T();
          return new T(*static_cast(t));
      }
      

    and note their usage of the copy constructor. This being the case, you have two ways around the problem:

    1) Provide a copy constructor (which you have done)

    2) Provide a specialization of qMetaTypeConstructHelper that doesn't use the copy constructor:

    template <>
    void *qMetaTypeConstructHelper(const ClassA *)
    {
        return new ClassA();
    }
    

提交回复
热议问题