自定义类型的头文件以及自定义类型声明和到处,否则可能会报如下错误:

头文件:
struct student
{
int iNo;
QString strname;
int age;
};
Q_DECLARE_METATYPE(student)源文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QVariant>
#include<QDebug>
#include<QColor>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QVariant qv1(259);
qDebug()<<"qv1:" << qv1.toInt();
QVariant qv2("Hello");
qDebug()<<"qv2: " << qv2.toString();
QMap<QString, QVariant> qmap;
qmap["int"] = 2025;
qmap["double"] = 3.14;
qmap["string"] = "world";
qmap["color"] = QColor(255,255,0);
qDebug()<<qmap;
qDebug()<<qmap["int"] << qmap["int"].toInt();
qDebug()<<qmap["double"] << qmap["double"].toDouble();
qDebug()<<qmap["string"] << qmap["string"].toString();
qDebug()<<qmap["color"] << qmap["color"].value<QColor>();
QVariant qv3;
//类似于var 在初次赋值的时候决定类型
qv3 = 17.9;
qDebug()<<qv3;
QStringList qsl;
qsl << "A" <<"b"<<"C" <<"d" <<"e" <<"F";
QVariant qvsl(qsl);
if(qvsl.type() == QVariant::StringList)
{
QStringList qlist = qvsl.toStringList();
for(int i = 0 ; i < qlist.size(); i++)
qDebug()<< qlist.at(i);
}
//应用自定义类型和QVariant配合使用
student stu;
stu.age = 18;
stu.iNo =1;
stu.strname = "zhangsan";
QVariant qstu = QVariant::fromValue(stu); //使用静态方法保存数据
if(qstu.canConvert<student>())
{
student t_stu = qstu.value<student>(); //获取数据
student t_stu2 = qvariant_cast<student>(qstu); //类型转换
qDebug()<<"student :{ ino = " << t_stu.iNo
<< "name = " << t_stu.strname
<< "age = " << t_stu.age;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
所有示例运行结果如下:

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。