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();
}

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

相关推荐
染指111011 分钟前
147.Agent-LangGraph归并函数
开发语言·人工智能·python·langchain·agents
Elastic 中国社区官方博客18 分钟前
教程:监控 Java 应用
java·开发语言·数据库·elasticsearch·搜索引擎·全文检索
ShineWinsu24 分钟前
对于JavaScript:初识JavaScript以及输入输出
java·开发语言·前端·javascript·css·面试·html
小小安于乱27 分钟前
linux中java的springboot程序获取IP地址间歇性10秒卡顿问题
java·开发语言
峥嵘life1 小时前
Android16 开机后立即打开相机闪退问题分析与解决总结
android·开发语言·数码相机·策略模式
niucloud-admin1 小时前
NIUCLOUD LITE AI开发文档--命名规范
开发语言·php
WL学习笔记1 小时前
模板初阶(C++)
开发语言·c++·后端·模板初阶
SunnyDays10111 小时前
使用 Java 高效管理 Excel 批注:添加、读取、修改和删除
java·开发语言·excel
ydjs678899-bot1 小时前
为什么大型monorepos变慢了Rush.js + Sparo对此做了什么
开发语言·javascript·ecmascript
坊钰1 小时前
【LangGraph框架入门级】12. 人机交互:interrupt 中断与 Command 恢复
开发语言·数据库·python·人机交互·ai编程·langgraph