您好,欢迎来到纷纭教育。
搜索
您的当前位置:首页Qt:QVariant的使用

Qt:QVariant的使用

来源:纷纭教育

前言

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;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- fenyunshixun.cn 版权所有 湘ICP备2023022495号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务