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

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

相关推荐
朝新_1 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir1 小时前
Calendar类日期设置进位问题
java·开发语言
风逸hhh2 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮3 小时前
Python训练第四十三天
开发语言·python
ascarl20104 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc4 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗4 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长4 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao5 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码5 小时前
STL解析——list的使用
开发语言·c++