QVariant使用例子
时间: 2023-07-11 15:27:08 浏览: 63
下面是一个使用QVariant的例子:
```cpp
#include <QVariant>
#include <QString>
#include <QDebug>
int main()
{
QVariant var;
// 存储int类型数据
int i = 123;
var.setValue(i);
qDebug() << var.typeName() << var.toInt();
// 存储QString类型数据
QString str = "hello";
var.setValue(str);
qDebug() << var.typeName() << var.toString();
// 判断是否支持类型转换
qDebug() << var.canConvert<int>();
qDebug() << var.canConvert<QString>();
// 获取对应类型的值
int j = var.value<int>();
QString s = var.value<QString>();
qDebug() << j << s;
return 0;
}
```
运行结果:
```
int 123
QString "hello"
true
true
123 "hello"
```
在这个例子中,我们首先创建了一个QVariant对象 var,然后使用 setValue() 方法存储了一个int类型的值和一个QString类型的值。可以通过 typeName() 方法获取存储的数据类型,通过 toInt() 和 toString() 方法获取对应类型的值。
接着,我们使用 canConvert() 方法判断QVariant对象是否支持类型转换,使用 value() 方法分别获取int和QString类型的值,最后使用 qDebug() 输出了这两个值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)