QVariant类

来源:互联网 发布:张量与矩阵的乘积 编辑:程序博客网 时间:2024/06/04 19:21

QVariant类的用法:
新建Qt Widgets Application,
项目名称为“myVariant”,
基类选择“QWidget”,
类名保持“Widget”不变,
取消选择“创建界面”复选框。
建好项目后,在widget.cpp文件中编写代码,具体内容。

#include "widget.h"#include <QDebug>#include <QVariant>#include <QColor>Widget::Widget(QWidget *parent)    : QWidget(parent){    QVariant v(709);    //声明一个QVariant变量v,并初始化为一个整数。    qDebug()<<v.toInt();    //调用QVariant::toInt()函数将QVariant变量包含的内容转换为整数并输出。    QVariant w("How are you! ");    //声明一个QVariant变量w,并初始化为一个字符串。    qDebug()<<w.toString();    //调用QVariant::toString()函数将QVariant变量包含的内容转换为字符串并输出。    QMap<QString,QVariant>map;    //声明一个QMap变量map,使用字符串作为键,QVariant变量作为值。    map["int"]=709;    map["double"]=709.709;    map["string"]="How are you! ";    map["color"]=QColor(255,0,0);    qDebug()<<map["int"]<< map["int"].toInt();    qDebug()<<map["double"]<< map["double"].toDouble();    qDebug()<<map["string"]<< map["string"].toString();    qDebug()<<map["color"]<< map["color"].value<QColor>();    //在QVariant变量中保存了一个QColor对象,并使用模板QVariant::value()还原为QColor,然后输出。    QStringList sl;    sl<<"A"<<"B"<<"C"<<"D";    QVariant slv(sl);    if(slv.type()==QVariant::StringList)    //QVariant::type()函数返回存储在QVariant变量中的值的数据类型。QVariant::StringList是Qt定义的一个QVariant::type枚举类型的变量    {        QStringList list=slv.toStringList();        for(int i=0;i<list.size();++i)            qDebug()<<list.at(i);    }}

这里写图片描述
最后,运行上述程序的结果如下:
 
709
“How are you! ”
QVariant(int,709) 709
QVariant(double,709.709) 709.709
QVariant(QString, “How are you! “) “How are you! ”
QVariant(QColor, QColor(ARGB 1,1,0,0)) QColor(ARGB 1,1,0,0)
“A”
“B”
“C”
“D”

0 0
原创粉丝点击