qt 如何注册自定义类型?

  1. 如何声明自定义类型
    如果仅仅在 QVariant 中使用,则仅需要使用 Q_DECLARE_METATYPE 宏进行声明即可。
class Custom_ : public QObject
{
    Q_OBJECT
public:
    Custom_() {}
    virtual ~Custom_() {}
};
//注意:继承 QObject 类型仅支持注册指针类型
Q_DECLARE_METATYPE(Custom_*)

class Custom
{
public:
    Custom() {}
    QString name(){return "custom";}
};
Q_DECLARE_METATYPE(Custom)
  1. 如何在 QVariant 中使用?
    T QVariant::value() const
    void QVariant::setValue(const T &value)
    [static] QVariant QVariant::fromValue(const T &value)
QVariant var;
Custom custom;
var.set<Custom>(custom);

QString name = var.value<Custom>().name();

//
auto var = QVariant::fromValue<Custom_*>(new Custom_);
auto custom_ = var.value<Custom_*>();
if(custom_){
    //
}

如何需要在信号和槽中使用则需要额外调用 qRegisterMetaType<Custom>("Custom") qRegisterMetaType<Custom_*>("Custom_")进行注册该类型.

使用 Q_DECLARE_METATYPE 宏,不会保证第一时间进行注册该类型,需要调用该函数才会执行 qRegisterMetaType,so 我们需要手动第一时间进行注册该类型。

#ifndef Q_MOC_RUN
#define Q_DECLARE_METATYPE(TYPE) Q_DECLARE_METATYPE_IMPL(TYPE)
#define Q_DECLARE_METATYPE_IMPL(TYPE)                                   \
    QT_BEGIN_NAMESPACE                                                  \
    template <>                                                         \
    struct QMetaTypeId< TYPE >                                          \
    {                                                                   \
        enum { Defined = 1 };                                           \
        static int qt_metatype_id()                                     \
            {                                                           \
                static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
                if (const int id = metatype_id.loadAcquire())           \
                    return id;                                          \
                const int newId = qRegisterMetaType< TYPE >(#TYPE,      \
                              reinterpret_cast< TYPE *>(quintptr(-1))); \
                metatype_id.storeRelease(newId);                        \
                return newId;                                           \
            }                                                           \
    };                                                                  \
    QT_END_NAMESPACE
#endif // Q_MOC_RUN
posted @ 2019-11-05 10:22  學海無涯  阅读(2202)  评论(0编辑  收藏  举报