zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    听说在新的一年里你的证书过期了
    css 清楚浮动的8种方式
    Majority Element:主元素
    HDOJ 5296 Annoying problem LCA+数据结构
    hdu 5318 The Goddess Of The Moon 矩阵高速幂
    友盟页面统计
    用html语言写一个功课表
    苹果新的编程语言 Swift 语言进阶(二)--基本数据类型
    Atitit.mssql 数据库表记录数and 表体积大小统计
    jeecms 代码生成 Tools
  • 原文地址:https://www.cnblogs.com/cheungxiongwei/p/11796839.html
Copyright © 2011-2022 走看看