QT使用boost.pfr结构体历遍,树显示

历遍函数:boost::pfr::for_each_field(obj, \&(const auto& field, std::size_t idx)

可惜的是,需要手动添加变量名。

cpp 复制代码
#include <QApplication>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <boost/pfr.hpp>
#include <QDebug>

struct StructA {
    int a;
    float b;
    char c;
};

struct StructB {
    int a;
    float b;
    StructA c;
};

struct StructC {
    StructA a;
    StructB b;
    char c;
};

// 递归函数,将结构体成员及其变量名添加到QTreeWidgetItem中
template <typename T, typename Names>
void addFieldsToItem(QTreeWidgetItem* parentItem, const T& obj, const Names& names) {
    boost::pfr::for_each_field(obj, [&](const auto& field, std::size_t idx) {
        if constexpr (std::is_same_v<std::decay_t<decltype(field)>, StructA> ||
                      std::is_same_v<std::decay_t<decltype(field)>, StructB>) {
            auto* childItem = new QTreeWidgetItem(parentItem);
            childItem->setText(0, std::string(names[idx]).c_str());
            addFieldsToItem(childItem, field, names);
        } else {
            auto* childItem = new QTreeWidgetItem(parentItem);
            childItem->setText(0, QString("%1: %2").arg(std::string(names[idx]).c_str()).arg(QString::number(field)));
        }
    });
}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QTreeWidget treeWidget;
    treeWidget.setHeaderLabel("Structures");

    StructC rootStruct = {{10, 3.14f, 'A'}, {20, 2.71f, {30, 1.41f, 'B'}}, 'C'};

    // 手动指定变量名
    const std::array<const char*, 3> structCNames = {"a", "b", "c"};
    const std::array<const char*, 3> structBNames = {"a", "b", "c"};
    const std::array<const char*, 3> structANames = {"a", "b", "c"};

    auto* rootItem = new QTreeWidgetItem(&treeWidget);
    rootItem->setText(0, "StructC");
    addFieldsToItem(rootItem, rootStruct, structCNames);

    treeWidget.addTopLevelItem(rootItem);
    treeWidget.expandAll();
    treeWidget.show();

    return app.exec();
}

上个版本的半自动结构体历遍

相关推荐
xiaoshuaishuai828 分钟前
C# AvaloniaUI动态显示图片
开发语言·c#
日光明媚42 分钟前
一步生成视频!One-Forcing:DMD + 零成本 GAN,训练 200 步超越多步 SOTA
android·开发语言·kotlin
2301_803538951 小时前
Java读取Word图片的两种实用方法
java·开发语言·word
bug和崩溃我都要3 小时前
Qt 封装 libmpv 全功能视频播放器开发指南
开发语言·qt·音视频
郝学胜-神的一滴3 小时前
Qt 高级开发 018:复刻经典登录界面布局与窗口美化全解析
开发语言·c++·qt·程序人生·用户界面
郝亚军3 小时前
IEEE 754 单精度浮点的SEM表示
开发语言·c++·算法
zhangjw343 小时前
第15篇:Java多线程零基础入门,进程线程、线程创建方式、线程生命周期、线程安全彻底吃透
java·开发语言·面试
蝈理塘(/_\)大怨种3 小时前
类和对象 (上)
java·开发语言
小新1103 小时前
qt creator 将qInfo的输出日志写入日志文档,方便查看
开发语言·qt
hssfscv4 小时前
QT的学习记录1
开发语言·qt·学习