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

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

相关推荐
Kiri霧42 分钟前
Linux下的Rust 与 C 的互操作性解析
c语言·开发语言·rust
雪芽蓝域zzs1 小时前
uniapp AES 加密解密
开发语言·uni-app·c#
雨夜的星光1 小时前
Python JSON处理:load/loads/dump/dumps全解析
开发语言·python·json
fen_fen2 小时前
Java打包时,不将本地Jar打包到项目的最终 JAR 中
开发语言·python·pycharm
weixin_464307634 小时前
QT中加载PSQL驱动
qt
wjs20244 小时前
SQL AND & OR 操作符详解
开发语言
~光~~5 小时前
【环境配置 】WSL2 +ubuntu20.04 +Qt配置+Kits配置
开发语言·qt·ubuntu
·心猿意码·5 小时前
C++右值语义解析
开发语言·c++
小龙报5 小时前
《彻底理解C语言指针全攻略(2)》
c语言·开发语言·c++·visualstudio·github·学习方法
zzzsde6 小时前
【c++】深入理解string类(4)
开发语言·c++