一個關於QVariant類的簡單用法示例:
<span style="font-family:Microsoft YaHei;font-size:18px;">#include "widget.h"
#include<QDebug>
#include<QVariant>
#include<QColor>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QVariant v(709);//聲明並初始化一個整數變量
qDebug()<<v.toInt();//變爲整數輸出
QVariant w("How are you!");
qDebug()<<w.toString();
QMap<QString,QVariant>map;//聲明一個QMap變量map,使用字符串爲鍵,QVariant變量爲值
map["int"]=709;//輸入整數型
map["String"]="How are you!";
map["double"]=709.709;
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.value()還原爲QColor輸出
QStringList sl;//創建一個字符串列表
sl<<"A"<<"B"<<"C"<<"D";//爲列表賦值
QVariant slv(sl);//將列表保存在QVariant變量中
if(slv.type()==QVariant::StringList)//
{
QStringList list=slv.toStringList();
for(int i=0;i<list.size();++i)
qDebug()<<list.at(i);
}
}
Widget::~Widget()
{
}</span>
結果如下所示: