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

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

相关推荐
刚入门的大一新生27 分钟前
C++初阶-C++入门基础
开发语言·c++
你是理想33 分钟前
wait 和notify ,notifyAll,sleep
java·开发语言·jvm
forestsea1 小时前
Python进阶编程总结
开发语言·python·notepad++
q567315231 小时前
使用Java的HttpClient实现文件下载器
java·开发语言·爬虫·scrapy
SunkingYang2 小时前
QT中怎么隐藏或显示最大化、最小化、关闭按钮
qt·关闭按钮·隐藏·显示·最大化按钮·最小化按钮
六bring个六2 小时前
QT上位机笔记
开发语言·笔记·qt
步木木2 小时前
Qt 5.14.2入门(一)写个Hello Qt!程序
开发语言·qt
techdashen2 小时前
Rust主流框架性能比拼: Actix vs Axum vs Rocket
开发语言·后端·rust
普通网友2 小时前
内置AI与浏览器的开源终端Wave Terminal安装与远程连接内网服务器教程
开发语言·后端·golang
南玖yy2 小时前
探索 C 语言数据结构:从基础到实践
c语言·开发语言·数据结构