Qt QVariant 与 自定义类型转换的方法
Example:
1. 声明自定义类型可用于QVariant,类也能用,也是这样,QT的基本数据类型不用声明就可以用,而且存入是什么类型,拿出来还是什么类型
#include <QMetaType>// Important,这个头文件
#include <iostream>
struct Student{
int id;
std::string name;
std::string email;
};
Q_DECLARE_METATYPE(Student)//和 这句注册?声明的话
2. 转换
QVariant variant = QVariant::fromValue(Student());//从 student 的对象转化过来的 QVariant 对象
if(variant.canConvert<Student>()){//判断防止空指针
Student stu = variant.value<Student>();//用value方法带上转换的类型就是了
}