Outline
QVariant may be used as a container, you can go into other types of values, and then may be removed.
When you want a type, which can store values of different types, can be used QVariant.
QVariant data types that can be saved QString, QImage, QFont, QPixmap, QPoint QT other built-in type, as well as C ++ basic types, such as int, float like. QSettings database module and the module are heavily dependent QVariant class.
Code
1. Press overloading to achieve
For example, I want to write a function can accept different types of parameters, I can use the function overloading to achieve:
main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QPoint>
//函数重载实现 show()
void show(int i)
{
qDebug()<<i;
}
void show(float f)
{
qDebug()<<f;
}
void show(QString s)
{
qDebug()<<s;
}
void show(QPoint p)
{
qDebug()<<p;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int i=123;
float f=1.23;
QString s="nuaa";
QPoint p(10,20);
//调用重载函数
show(i);
show(f);
show(s);
show(p);
return a.exec();
}
Output:
1. Use to achieve QVariant
main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QPoint>
//QVariant实现
void Varshow(QVariant v)
{
if(v.type()==QMetaType::Int){
int i=v.value<int>();
qDebug()<<i;
}
else if(v.type()==QMetaType::Float){
float f=v.value<float>();
qDebug()<<f;
}
else if(v.type()==QMetaType::QString){
QString s=v.value<QString>();
qDebug()<<s;
}
else if(v.type()==QMetaType::QPoint){
QPoint p=v.value<QPoint>();
qDebug()<<p;
}
else
qDebug()<<"未定义的传入类型!";
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int i=123;
float f=1.23;
QString s="nuaa";
QPoint p(10,20);
//调用函数
Varshow(i);
Varshow(f);
Varshow(s);
Varshow(p);
return a.exec();
}
Output:
Although the amount of code seems no difference, but in a medium or large software, especially to the frequent use of different types binary signal slot value is passed, the use QVariant a lot easier than using function overloading.