什么是 QVariant?
QVariant 是 Qt 中的一个类,允许您以一种通用的方式存储和访问数据,即使这些数据具有不同的数据类型。它在许多情况下非常有用,例如在模型视图编程、数据序列化、设置和配置管理等领域。QVariant 可以包含以下类型的数据:
基本数据类型,如整数、浮点数、布尔值、枚举等。
Qt 内置的数据类型,如 QString、QByteArray、QDate、QTime、QDateTime 等。
用户自定义的数据类型,只要您为其定义了 QVariant 转换函数
丰富的示例
#include <QCoreApplication>
#include <QVariant>
#include <QDebug>
#include <QDate>
#include <QTime>
#include <QDateTime>
#include <QByteArray>
#include <QStringList>
#include <QColor>
#include <QFont>
#include <QPoint>
#include <QSize>
#include <QRect>
#include <QMetaType>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);// 创建一个QVariant对象并设置其值QVariant var;// 1. 整数int intValue = 42;var = QVariant(intValue);// 2. 浮点数double doubleValue = 3.14159;var = QVariant(doubleValue);// 3. 字符串QString stringValue = "Hello, QVariant!";var = QVariant(stringValue);// 4. 布尔值bool boolValue = true;var = QVariant(boolValue);// 5. 列表QVariantList list;list.append(1);list.append("Two");list.append(3.0);var = QVariant(list);// 6. MapQVariantMap map;map["name"] = "Alice";map["age"] = 30;map["isStudent"] = false;var = QVariant(map);// 7. 枚举enum Color { Red, Green, Blue };Color colorValue = Blue;var = QVariant(colorValue);// 8. 自定义类型class CustomType {public:int value;QString name;};CustomType customValue;customValue.value = 123;customValue.name = "Custom";var = QVariant::fromValue(customValue);// 9. 数据类型检查if (var.type() == QVariant::Int) {int intValue = var.toInt();}// 10. 数据类型转换QString strValue = var.toString();// 11. 比较QVariant anotherIntValue = QVariant(42);if (var == anotherIntValue) {qDebug() << "var is equal to anotherIntValue";}// 12. 访问Map中的值QVariantMap mapValue = var.toMap();QString name = mapValue["name"].toString();int age = mapValue["age"].toInt();// 13. 获取枚举值名称QString enumName = var.typeName();// 14. 清空QVariantvar.clear();// 15. 判断QVariant是否为空if (var.isNull()) {qDebug() << "var is null";}// 其他高级方法:// 16. QVariant类型的自省QVariant::Type type = var.type();// 17. QVariant的详细类型信息const QMetaObject *metaObject = var.metaObject();// 18. 类型是否可转换bool canConvert = var.canConvert(QVariant::Int);// 19. 从字符串创建QVariantQVariant fromStringVar = QVariant::fromValue("42");// 20. 将QVariant转为JSONQJsonObject jsonObject = var.toJsonValue().toObject();// 21. 将JSON转为QVariantQVariant fromJsonVar = QVariant::fromValue(jsonObject);// 22. 根据类型名创建QVariantQVariant typeVar = QVariant::fromType(QMetaType::Int);// 23. 使用 QVariantList 创建 QVariantQVariantList listVar;listVar << 1 << 2 << 3;// 24. 使用 QVariantMap 创建 QVariantQVariantMap mapVar;mapVar["name"] = "John";mapVar["age"] = 25;// 25. QVariant的复制QVariant copyVar = var;// 26. 使用 QVariantList 创建 QVariantQVariantList listVar2 = QVariantList() << 4 << 5 << 6;// 27. 检查是否有值if (var.isValid()) {qDebug() << "var is valid";}// 28. 获取 QVariant 内部数据指针const void *dataPtr = var.constData();// 29. 获取 QVariant 内部数据大小int dataSize = var.dataSize();// 30. 使用自定义转换函数QVariant customConvertedVar = var.value<CustomType>();// 31. QDateQDate dateValue(2023, 11, 4);var = QVariant(dateValue);// 32. QTimeQTime timeValue(14, 30);var = QVariant(timeValue);// 33. QDateTimeQDateTime dateTimeValue(QDate(2023, 11, 4), QTime(14, 30));var = QVariant(dateTimeValue);// 34. QByteArrayQByteArray byteArrayValue = QByteArray("Hello, QVariant!");var = QVariant(byteArrayValue);// 35. QStringListQStringList stringListValue;stringListValue << "One" << "Two" << "Three";var = QVariant(stringListValue);// 36. QColorQColor colorValue(255, 0, 0); // 红色var = QVariant(colorValue);// 37. QFontQFont fontValue("Arial", 12);var = QVariant(fontValue);// 38. QPointQPoint pointValue(100, 200);var = QVariant(pointValue);// 39. QSizeQSize sizeValue(300, 400);var = QVariant(sizeValue);// 40. QRectQRect rectValue(100, 100, 300, 200);var = QVariant(rectValue);// 41. QVariantList,嵌套QVariantQVariantList nestedList;nestedList << QVariant(1) << QVariant("Nested") << QVariant(3.0);QVariant nestedVar = QVariant(nestedList);var = QVariant(nestedVar);// 42. QVariantMap,嵌套QVariantQVariantMap nestedMap;nestedMap["key1"] = QVariant(42);nestedMap["key2"] = QVariant("Nested");QVariant nestedMapVar = QVariant(nestedMap);var = QVariant(nestedMapVar);// 43. 多个类型混合的QVariantListQVariantList mixedList;mixedList << QVariant(42) << QVariant("Mixed") << QVariant(QDate(2023, 11, 4));var = QVariant(mixedList);// 44. 使用toXxx()函数获取值int intValue = var.toInt();double doubleValue = var.toDouble();QString stringValue = var.toString();QDate date = var.toDate();QTime time = var.toTime();QDateTime dateTime = var.toDateTime();QByteArray byteArray = var.toByteArray();QStringList stringList = var.toStringList();QColor color = var.value<QColor>();QFont font = var.value<QFont>();QPoint point = var.value<QPoint>();QSize size = var.value<QSize>();QRect rect = var.value<QRect>();// 45. 使用value<T>()函数获取自定义类型class CustomType {public:int value;QString name;};CustomType customValue = var.value<CustomType>();// 46. 使用constData()获取数据指针const void *dataPtr = var.constData();// 47. 检查是否为空if (var.isNull()) {qDebug() << "var is null";}// 48. 获取类型名称QString typeName = var.typeName();// 49. 将QVariant转为JSON字符串QString jsonStr = QVariant::fromValue(var).toJsonValue().toString();// 50. 从JSON字符串创建QVariantQVariant fromJsonVar = QVariant::fromValue(QJsonDocument::fromJson(jsonStr.toUtf8()).toVariant());// 51. QListQList<int> intList;intList << 1 << 2 << 3;var = QVariant::fromValue(intList);// 52. QVectorQVector<QString> stringVector;stringVector << "One" << "Two" << "Three";var = QVariant::fromValue(stringVector);// 53. QMapQMap<QString, int> stringIntMap;stringIntMap["One"] = 1;stringIntMap["Two"] = 2;var = QVariant::fromValue(stringIntMap);// 54. QStringListQStringList stringList;stringList << "Apple" << "Banana" << "Cherry";var = QVariant::fromValue(stringList);// 55. QVariantList,混合数据类型QVariantList mixedDataList;mixedDataList << 42 << "Mixed" << 3.14;var = QVariant(mixedDataList);// 56. QVariantMap,混合数据类型QVariantMap mixedDataMap;mixedDataMap["key1"] = 42;mixedDataMap["key2"] = "Mixed";mixedDataMap["key3"] = 3.14;var = QVariant(mixedDataMap);// 57. QVariantList,深度嵌套QVariantList deepNestedList;QVariantList innerList;innerList << 1 << 2 << 3;deepNestedList << innerList << "Nested" << 3.14;var = QVariant(deepNestedList);// 58. QVariantMap,深度嵌套QVariantMap deepNestedMap;QVariantMap innerMap;innerMap["key1"] = 42;innerMap["key2"] = "Nested";deepNestedMap["inner"] = innerMap;deepNestedMap["key3"] = 3.14;var = QVariant(deepNestedMap);// 59. QVariantMap,枚举类型enum Fruit { Apple, Banana, Cherry };QVariantMap enumMap;enumMap["fruit"] = Fruit::Apple;var = QVariant(enumMap);// 60. QVariantList,枚举类型QVariantList enumList;enumList << Fruit::Apple << Fruit::Banana << Fruit::Cherry;var = QVariant(enumList);// 61. QVariantList,指针类型int* intPointer = new int(42);var = QVariant::fromValue(intPointer);// 62. QVariantList,QSharedPointer类型QSharedPointer<int> sharedInt = QSharedPointer<int>(new int(42));var = QVariant::fromValue(sharedInt);// 63. QVariantList,自定义类指针class CustomType {public:int value;QString name;};CustomType* customPointer = new CustomType();customPointer->value = 42;customPointer->name = "CustomPointer";var = QVariant::fromValue(customPointer);// 64. QVariantList,QList指针QList<int>* intListPointer = new QList<int>();intListPointer->append(1);intListPointer->append(2);intListPointer->append(3);var = QVariant::fromValue(intListPointer);// 65. QVariantList,QMap指针QMap<QString, int>* stringIntMapPointer = new QMap<QString, int>();stringIntMapPointer->insert("One", 1);stringIntMapPointer->insert("Two", 2);var = QVariant::fromValue(stringIntMapPointer);// 66. QVariantList,QVariantList指针QVariantList* nestedListPointer = new QVariantList();nestedListPointer->append(1);nestedListPointer->append("Nested");var = QVariant::fromValue(nestedListPointer);// 67. QVariantList,QVariantMap指针QVariantMap* nestedMapPointer = new QVariantMap();(*nestedMapPointer)["key1"] = 42;(*nestedMapPointer)["key2"] = "Nested";var = QVariant::fromValue(nestedMapPointer);// 68. QVariantList,复合结构struct ComplexStruct {int intValue;QString stringValue;QMap<QString, QVariant> dataMap;};ComplexStruct complexValue = {42, "Complex", stringIntMap};var = QVariant::fromValue(complexValue);// 69. QVariantList,QVariant指针QVariant* varPointer = new QVariant(42);var = QVariant::fromValue(varPointer);// 70. QVariantList,QVariantList指针QVariantList* varListPointer = new QVariantList();varListPointer->append(1);varListPointer->append("Nested");var = QVariant::fromValue(varListPointer);// 71. QVariantList,QVariantMap指针QVariantMap* varMapPointer = new QVariantMap();(*varMapPointer)["key1"] = 42;(*varMapPointer)["key2"] = "Nested";var = QVariant::fromValue(varMapPointer);// 72. 检查是否包含特定类型if (var.canConvert(QVariant::Int)) {int convertedInt = var.toInt();qDebug() << "Can convert to int: " << convertedInt;}// 73. 检查是否包含特定自定义类型bool hasCustomType = QMetaType::type("CustomType") != QMetaType::UnknownType;if (hasCustomType && var.canConvert(QMetaType::type("CustomType"))) {CustomType custom = var.value<CustomType>();qDebug() << "Can convert to CustomType: " << custom.value << custom.name;}// 74. 使用 QVariantList 遍历QVariantMapQVariantMap mapInList;mapInList["name"] = "John";mapInList["age"] = 30;QVariantList listInMap;listInMap << 1 << 2 << mapInList;QVariantMap mapWithList;mapWithList["data"] = listInMap;var = QVariant(mapWithList);QVariantList nestedDataList = var.toMap()["data"].toList();for (const QVariant& item : nestedDataList) {if (item.canConvert(QVariant::String)) {QString strValue = item.toString();qDebug() << "String in nested list: " << strValue;}else if (item.canConvert(QVariant::Map)) {QVariantMap mapValue = item.toMap();QString name = mapValue["name"].toString();int age = mapValue["age"].toInt();qDebug() << "Map in nested list: Name - " << name << ", Age - " << age;}}// 75. 使用 QVariantMap 遍历QVariantMapQVariantMap mapData;mapData["key1"] = 42;mapData["key2"] = "Value";mapData["key3"] = 3.14;var = QVariant(mapData);QVariantMap dataMap = var.toMap();for (const QString& key : dataMap.keys()) {QVariant value = dataMap[key];if (value.canConvert(QVariant::Int)) {int intValue = value.toInt();qDebug() << "Key: " << key << " - Int Value: " << intValue;}else if (value.canConvert(QVariant::String)) {QString strValue = value.toString();qDebug() << "Key: " << key << " - String Value: " << strValue;}else if (value.canConvert(QVariant::Double)) {double doubleValue = value.toDouble();qDebug() << "Key: " << key << " - Double Value: " << doubleValue;}}// 76. QVariantList 转换为数组QVariantList listToConvert;listToConvert << 1 << 2 << 3 << 4 << 5;int* intArray = listToConvert.data<int>();for (int i = 0; i < listToConvert.size(); ++i) {qDebug() << "Array Value: " << intArray[i];}// 77. QVariantList 转换为自定义类数组class CustomType {public:int value;QString name;};QVariantList customList;CustomType custom1 = {1, "One"};CustomType custom2 = {2, "Two"};CustomType custom3 = {3, "Three"};customList << QVariant::fromValue(custom1) << QVariant::fromValue(custom2) << QVariant::fromValue(custom3);CustomType* customArray = customList.data<CustomType>();for (int i = 0; i < customList.size(); ++i) {qDebug() << "Custom Array Value: " << customArray[i].value << customArray[i].name;}// 78. 使用 QVariantList 进行排序QVariantList sortList;sortList << 5 << 2 << 1 << 4 << 3;std::sort(sortList.begin(), sortList.end(), [](const QVariant& a, const QVariant& b) {return a.toInt() < b.toInt();});qDebug() << "Sorted List: " << sortList;// 79. 使用 QVariantList 进行过滤QVariantList filterList;filterList << 1 << 2 << 3 << 4 << 5;QVariantList filtered = filterList.filter([](const QVariant& value) {return value.toInt() % 2 == 0;});qDebug() << "Filtered List: " << filtered;// 80. 使用 QVariantList 进行映射QVariantList mapList;mapList << 1 << 2 << 3;QVariantList mapped = mapList.map([](const QVariant& value) {return value.toInt() * 2;});qDebug() << "Mapped List: " << mapped;// 81. 使用 QVariantList 进行折叠QVariantList foldList;foldList << 1 << 2 << 3 << 4 << 5;int sum = foldList.fold(0, [](int accumulator, const QVariant& value) {return accumulator + value.toInt();});qDebug() << "Folded Sum: " << sum;// 82. 使用 QVariantList 进行查找QVariantList findList;findList << 10 << 20 << 30 << 40 << 50;QVariant found = findList.find([](const QVariant& value) {return value.toInt() == 30;});qDebug() << "Found Value: " << found;// 83. 使用 QVariantList 进行去重QVariantList duplicateList;duplicateList << 1 << 2 << 3 << 2 << 1;QVariantList unique = duplicateList.unique();qDebug() << "Unique List: " << unique;// 84. 使用 QVariantMap 进行排序QVariantMap sortMap;sortMap["one"] = 5;sortMap["two"] = 2;sortMap["three"] = 1;QVariantMap sortedMap = sortMap.sortedKeys();qDebug() << "Sorted Map: " << sortedMap;// 85. 使用 QVariantMap 进行过滤QVariantMap filterMap;filterMap["one"] = 1;filterMap["two"] = 2;filterMap["three"] = 3;QVariantMap filteredMap = filterMap.filter([](const QVariant& key, const QVariant& value) {return value.toInt() % 2 == 0;});qDebug() << "Filtered Map: " << filteredMap;// 86. 使用 QVariantMap 进行映射QVariantMap mapMap;mapMap["one"] = 1;mapMap["two"] = 2;mapMap["three"] = 3;QVariantMap mappedMap = mapMap.map([](const QVariant& key, const QVariant& value) {return QVariant(key.toString() + "Squared", value.toInt() * value.toInt());});qDebug() << "Mapped Map: " << mappedMap;// 87. 使用 QVariantMap 进行折叠QVariantMap foldMap;foldMap["one"] = 1;foldMap["two"] = 2;foldMap["three"] = 3;int sumMap = foldMap.fold(0, [](int accumulator, const QVariant& key, const QVariant& value) {return accumulator + value.toInt();});qDebug() << "Folded Sum in Map: " << sumMap;return a.exec();
}