QVariant類
例:
#include <QDebug>
#include <QColor>
int main(int argc,char *argv[])
{
QVariant v(709);//聲明一個變量v並初始化爲整數
qDebug()<<v.toInt();
QVariant w("How are you! ");//聲明一個變量w並初始化爲字符串
qDebug()<<w.toString();
QMap<QString,QVariant>map;//聲明一個map容器,使用字符串爲Key,QVariant變量爲值
map["int"]=709;//將各類型數值存入map
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是QtCore模塊的類,沒有爲QtGUI模塊中的數據類型(QColor、QImage、QPixmap等)提供轉換函數,
//因此需要使用QVariant::value()或者QVariantValue()將其還原爲QColor
QStringList sl;//創建一個字符串列表
sl<<"A"<<"B"<<"C"<<"D";
QVariant slv(sl);//將該列表保存在一個QVariant變量中
if(slv.type()==QVariant::StringList)//返回存儲在QVariant變量中的值的數據類型
{
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"
常見的QVariant::type()枚舉類型變量: