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

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

相关推荐
always_TT2 分钟前
C语言中的“副作用”是什么?
c语言·开发语言
XiYang-DING28 分钟前
【Java SE】包装类(Wrapper Class)
java·开发语言
麦兜顶当当30 分钟前
subprocess与子进程交互
java·开发语言·jvm
Ulyanov35 分钟前
基于Tkinter/ttk的现代化Python GUI开发全攻略:从布局设计到视觉美化(三)
开发语言·python·gui·tkinter·ttk
hutengyi41 分钟前
go测试问题记录
开发语言·后端·golang
weixin_433179331 小时前
python - 读写文件
开发语言·python
東雪木1 小时前
java学习—— 8 种基本数据类型 vs 包装类、自动装箱 / 拆箱底层原理
java·开发语言·java面试
Lyyaoo.1 小时前
【JAVA基础面经】JVM、JRE、JDK
java·开发语言·jvm
liulilittle1 小时前
SQLite3增删改查(C
c语言·开发语言·数据库·c++·sqlite
左左右右左右摇晃1 小时前
ConcurrentHashMap 设计原理笔记
java·开发语言·笔记