前言
QVariant不仅支持多种Qt原生数据类型,而且还支持自定义数据类型,简直不要太好用
正文
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QPaintEvent>
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui
{
class Widget;
}
QT_END_NAMESPACE
// 自定义数据类型
struct Student
{
int id;
QString name;
Student() {}
};
// 需要在宏中声明自定义数据类型
Q_DECLARE_METATYPE(Student)
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget* parent = nullptr);
~Widget();
// 使用QVariant来封装普通类型的操作
QVariant addValue(QVariant a, QVariant b);
private:
Ui::Widget* ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <QDebug>
#include <QPoint>
#include <QVariant>
#include "ui_widget.h"
Widget::Widget(QWidget* parent)
: QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
QPoint a(22, 33), b(11, 12);
QPoint res = addValue(a, b).toPoint();
qDebug() << "点相加的结果:" << res;
// 使用QVariant来封装自定义类型的操作
Student s;
s.id = 1011;
s.name = "kangkang";
#if 1
QVariant v;
v.setValue(s);
#else
// 这两种方法效果一样
QVariant v = QVariant::fromValue(p);
#endif
// 取出v中数据
if (v.canConvert<Student>())
{
Student temp = v.value<Student>();
qDebug() << "id:" << temp.id << "name:" << temp.name;
}
}
Widget::~Widget() { delete ui; }
QVariant Widget::addValue(QVariant a, QVariant b)
{
QVariant ret;
// 这里可以封装更多的类型
if (a.type() == QVariant::Int && b.type() == QVariant::Int)
{
ret = QVariant(a.toInt() + b.toInt());
}
else if (a.type() == QVariant::String && b.type() == QVariant::String)
{
// 和上面效果一样
ret.setValue(a.toString() + b.toString());
}
else if (a.type() == QVariant::Point && b.type() == QVariant::Point)
{
ret.setValue(a.toPoint() + b.toPoint());
}
return ret;
}