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

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

相关推荐
m0_3807438712 分钟前
给 Claude API 调用补上超时重试和错误分类
开发语言·人工智能·php
Draw Stars21 分钟前
Git BASH安装教程
开发语言·git·bash
vortex528 分钟前
一文讲透 Zsh 与 Bash 的区别
开发语言·bash
千谦阙听32 分钟前
C++类和对象(中):默认成员函数、构造与析构、拷贝构造、运算符重载
开发语言·c++·学习
kaixin_learn_qt_ing3 小时前
Qt Model/View
qt
Quz4 小时前
QML MouseArea:鼠标拖拽与滚轮缩放
qt·qml
天下无敌笨笨熊4 小时前
C#Modbus串口开发心得
开发语言·c#
电商API_180079052474 小时前
电商商品价格监控工具淘宝京东商品价格抓取API项目实操分享
java·大数据·开发语言·前端·数据挖掘
zzzll11114 小时前
深度剖析:HashMap 并发死循环与 ConcurrentHashMap 两代演进全解
java·开发语言
如意猴4 小时前
【C++】001--C++入门(1)
开发语言·c++