自定義數據結構通過QVariant來存儲並通過QMetaType來判斷對應存儲類型


一般常用的int double等數據類型判別和代碼用例網上有很多,這里不做描述,這里只講自定義數據類型和QVariant的轉換操作。

(1) 自定義數據類型

 

 

自定義數據類型

注意一定要使用Q_DECLARE_METATYPE() 對自定義數據類型進行宏定義,否則無法轉換成QVariant

(2) 使用

① 自定義類型轉QVariant

 

② QVariant轉成自定義數據類型

 

(3) 注意一定要對自定義類型通過Q_DECLARE_METATYPE()進行宏定義轉換,Qt5.5.0文檔中解釋如下;

① Q_DECLARE_METATYPE( Type)

1) This macro makes the type Type known to QMetaType as long as it provides a public default constructor, a public copy constructor and a public destructor. It is needed to use the type Type as a custom type in QVariant.

2) This macro requires that Type is a fully defined type at the point where it is used. For pointer types, it also requires that the pointed to type is fully defined. Use in conjunction with Q_DECLARE_OPAQUE_POINTER() to register pointers to forward declared types.

3) Ideally, this macro should be placed below the declaration of the class or struct. If that is not possible, it can be put in a private header file which has to be included every time that type is used in a QVariant.

4) Adding a Q_DECLARE_METATYPE() makes the type known to all template based functions, including QVariant. Note that if you intend to use the type in queued signal and slot connections or in QObject's property system, you also have to call qRegisterMetaType() since the names are resolved at runtime.

② 硬核翻譯說明:

1) 只要該宏提供了公共默認構造函數、公共復制構造函數和公共析構函數,它就會使QMetaType知道該類型。QVariant中,需要將該類型用作自定義類型

2) 此宏要求該類型在使用時是完全定義的類型。對於指針類型,它還要求完全定義指向的類型。Q_DECLARE_OPAQUE_POINTER()結合使用,將指針注冊到前向聲明的類型。

3) 理想情況下,這個宏應該放在類或結構聲明的下面。如果這是不可能的,它可以放在一個私有頭文件中,每次在QVariant中使用該類型時都必須包含該頭文件

4) 添加Q_DECLARE_METATYPE()可以使所有基於模板的函數(包括QVariant)都知道該類型。請注意,如果要在排隊信號和插槽連接QObject的屬性系統中使用該類型,還必須調用qRegisterMetaType(),因為名稱在運行時解析


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM