网站 图文混编,dede视频网站,火锅料网站方案怎么做,域名怎么绑定网站QVariant类
QVariant类本质为C联合(Union)数据类型#xff0c;它可以保存很多Qt类型的值#xff0c;包括 QBrush#xff0c;QColor#xff0c;QString等等#xff0c;也能存放Qt的容器类型的值。
QVariant::StringList 是 Qt 定义的一个 QVariant::type 枚举类型的变量联合(Union)数据类型它可以保存很多Qt类型的值包括 QBrushQColorQString等等也能存放Qt的容器类型的值。
QVariant::StringList 是 Qt 定义的一个 QVariant::type 枚举类型的变量其他常用的枚举类型变量如下表所示 代码如下
main.cpp
#include mainwindow.h#include QApplicationint main(int argc, char *argv[])
{QApplication a(argc, argv);MainWindow w;w.show();return a.exec();
}mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include QMainWindowstruct student
{int iNo;QString strName;int score;
};
Q_DECLARE_METATYPE(student);class MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent nullptr);~MainWindow();
};
#endif // MAINWINDOW_Hmainwindow.cpp
#include mainwindow.h#include QVariant
#include QDebug
#include QColorMainWindow::MainWindow(QWidget *parent): QMainWindow(parent)
{QVariant qv1(298);qDebug()qv1:qv1.toInt();QVariant qv2(Hello World!);qDebug()qv2:qv2.toString();QMapQString,QVariant qmap;qDebug()endl;qmap[int]20000; // 整型qmap[double]99.88; // 浮点型qmap[string]GoodBye; // 字符串qmap[color]QColor(255,255,0); // QColor类型// 输出转换函数来处理qDebug()qmap[int]qmap[int].toInt();qDebug()qmap[double]qmap[double].toDouble();qDebug()qmap[string]qmap[int].toString();qDebug()qmap[color]qmap[int].valueQColor();// 创建一个字符串列表QStringListqDebug()endl;QStringList qsl;qslABCDEF;QVariant qvsl(qsl); // 将列表存储在一个QVariant变量if(qvsl.type()QVariant::StringList){QStringList qlistqvsl.toStringList();for(int i0;iqlist.size();i){qDebug()qlist.at(i); // 输出列表数据信息}}// 结构体类型和QVariant类配合使用qDebug()endl;student stu;stu.iNo202221;stu.strNamesunny;stu.score715;// 使用静态方法保存数据QVariant qstuQVariant::fromValue(stu);if(qstu.canConvertstudent()){student tempqstu.valuestudent(); //获取数据student qtempqvariant_caststudent(qstu); // 获取数据qDebug()student:iNotemp.iNo,strNametemp.strName.scoretemp.score;qDebug()student:iNoqtemp.iNo,strNameqtemp.strName.scoreqtemp.score;}}MainWindow::~MainWindow()
{
}
QVariant::fromValue()函数将自定义的student结构体对象stu转换为QVariant对象qstu。qstu.canConvert()函数检查QVariant对象qstu是否可以转换为student类型。student temp qstu.value()将QVariant对象qstu转换为student类型并将结果赋值给temp。student qtemp qvariant_cast(qstu)也可以将QVariant对象qstu转换为student类型并将结果赋值给qtemp。最后通过qDebug()输出转换后的student对象temp和qtemp的成员变量值。
结果如下