QtC++与QVariant详解

介绍

cpp 复制代码
#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. Map
    QVariantMap 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. 清空QVariant
    var.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. 从字符串创建QVariant
    QVariant fromStringVar = QVariant::fromValue("42");

    // 20. 将QVariant转为JSON
    QJsonObject jsonObject = var.toJsonValue().toObject();

    // 21. 将JSON转为QVariant
    QVariant fromJsonVar = QVariant::fromValue(jsonObject);

    // 22. 根据类型名创建QVariant
    QVariant typeVar = QVariant::fromType(QMetaType::Int);

    // 23. 使用 QVariantList 创建 QVariant
    QVariantList listVar;
    listVar << 1 << 2 << 3;

    // 24. 使用 QVariantMap 创建 QVariant
    QVariantMap mapVar;
    mapVar["name"] = "John";
    mapVar["age"] = 25;

    // 25. QVariant的复制
    QVariant copyVar = var;

    // 26. 使用 QVariantList 创建 QVariant
    QVariantList 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. QDate
    QDate dateValue(2023, 11, 4);
    var = QVariant(dateValue);

    // 32. QTime
    QTime timeValue(14, 30);
    var = QVariant(timeValue);

    // 33. QDateTime
    QDateTime dateTimeValue(QDate(2023, 11, 4), QTime(14, 30));
    var = QVariant(dateTimeValue);

    // 34. QByteArray
    QByteArray byteArrayValue = QByteArray("Hello, QVariant!");
    var = QVariant(byteArrayValue);

    // 35. QStringList
    QStringList stringListValue;
    stringListValue << "One" << "Two" << "Three";
    var = QVariant(stringListValue);

    // 36. QColor
    QColor colorValue(255, 0, 0); // 红色
    var = QVariant(colorValue);

    // 37. QFont
    QFont fontValue("Arial", 12);
    var = QVariant(fontValue);

    // 38. QPoint
    QPoint pointValue(100, 200);
    var = QVariant(pointValue);

    // 39. QSize
    QSize sizeValue(300, 400);
    var = QVariant(sizeValue);

    // 40. QRect
    QRect rectValue(100, 100, 300, 200);
    var = QVariant(rectValue);

    // 41. QVariantList,嵌套QVariant
    QVariantList nestedList;
    nestedList << QVariant(1) << QVariant("Nested") << QVariant(3.0);
    QVariant nestedVar = QVariant(nestedList);
    var = QVariant(nestedVar);

    // 42. QVariantMap,嵌套QVariant
    QVariantMap nestedMap;
    nestedMap["key1"] = QVariant(42);
    nestedMap["key2"] = QVariant("Nested");
    QVariant nestedMapVar = QVariant(nestedMap);
    var = QVariant(nestedMapVar);

    // 43. 多个类型混合的QVariantList
    QVariantList 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字符串创建QVariant
    QVariant fromJsonVar = QVariant::fromValue(QJsonDocument::fromJson(jsonStr.toUtf8()).toVariant());

// 51. QList
    QList<int> intList;
    intList << 1 << 2 << 3;
    var = QVariant::fromValue(intList);

    // 52. QVector
    QVector<QString> stringVector;
    stringVector << "One" << "Two" << "Three";
    var = QVariant::fromValue(stringVector);

    // 53. QMap
    QMap<QString, int> stringIntMap;
    stringIntMap["One"] = 1;
    stringIntMap["Two"] = 2;
    var = QVariant::fromValue(stringIntMap);

    // 54. QStringList
    QStringList 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 遍历QVariantMap
    QVariantMap 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 遍历QVariantMap
    QVariantMap 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();
}
相关推荐
芊寻(嵌入式)6 分钟前
C转C++学习笔记--基础知识摘录总结
开发语言·c++·笔记·学习
獨枭7 分钟前
C++ 项目中使用 .dll 和 .def 文件的操作指南
c++
霁月风10 分钟前
设计模式——观察者模式
c++·观察者模式·设计模式
橘色的喵11 分钟前
C++编程:避免因编译优化引发的多线程死锁问题
c++·多线程·memory·死锁·内存屏障·内存栅栏·memory barrier
一颗松鼠14 分钟前
JavaScript 闭包是什么?简单到看完就理解!
开发语言·前端·javascript·ecmascript
有梦想的咸鱼_16 分钟前
go实现并发安全hashtable 拉链法
开发语言·golang·哈希算法
海阔天空_201322 分钟前
Python pyautogui库:自动化操作的强大工具
运维·开发语言·python·青少年编程·自动化
天下皆白_唯我独黑29 分钟前
php 使用qrcode制作二维码图片
开发语言·php
夜雨翦春韭33 分钟前
Java中的动态代理
java·开发语言·aop·动态代理
小远yyds34 分钟前
前端Web用户 token 持久化
开发语言·前端·javascript·vue.js