历遍函数:boost::pfr::for_each_field(obj, [&](const auto& field, std::size_t idx)
可惜的是,需要手动添加变量名。
#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();
}
上个版本的半自动结构体历遍