Qt C++ 显示多级结构体,包括结构体名、变量名和值
QTreeView 和 QStandardItemModel 来实现。以下是实现这一功能的步骤和示例代码:
定义多级结构体:
假设你有一个多级结构体,如下所示:
struct SubStruct {
int subValue1;
QString subValue2;
};
struct MainStruct {
int mainValue1;
QString mainValue2;
SubStruct subStruct;
};
以下是完整的示例代码:
mainwindow.h
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStandardItemModel>
#include <QTreeView>
#include "structures.h" // 假设结构体定义在这个头文件中
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QTreeView *treeView;
QStandardItemModel *model;
void populateTree(const MainStruct &mainStruct, QStandardItem *parentItem);
};
mainwindow.cpp
#endif // MAINWINDOW_H
// mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
treeView = new QTreeView(this);
setCentralWidget(treeView);
model = new QStandardItemModel(this);
treeView->setModel(model);
MainStruct mainStruct;
mainStruct.mainValue1 = 10;
mainStruct.mainValue2 = "Main Value 2";
mainStruct.subStruct.subValue1 = 20;
mainStruct.subStruct.subValue2 = "Sub Value 2";
QStandardItem *rootItem = model->invisibleRootItem();
populateTree(mainStruct, rootItem);
}
MainWindow::~MainWindow()
{
}
void MainWindow::populateTree(const MainStruct &mainStruct, QStandardItem *parentItem)
{
QStandardItem *mainStructItem = new QStandardItem("MainStruct");
parentItem->appendRow(mainStructItem);
QStandardItem *mainValue1Item = new QStandardItem("mainValue1");
mainValue1Item->appendRow(new QStandardItem(QString::number(mainStruct.mainValue1)));
mainStructItem->appendRow(mainValue1Item);
QStandardItem *mainValue2Item = new QStandardItem("mainValue2");
mainValue2Item->appendRow(new QStandardItem(mainStruct.mainValue2));
mainStructItem->appendRow(mainValue2Item);
QStandardItem *subStructItem = new QStandardItem("SubStruct");
mainStructItem->appendRow(subStructItem);
QStandardItem *subValue1Item = new QStandardItem("subValue1");
subValue1Item->appendRow(new QStandardItem(QString::number(mainStruct.subStruct.subValue1)));
subStructItem->appendRow(subValue1Item);
QStandardItem *subValue2Item = new QStandardItem("subValue2");
subValue2Item->appendRow(new QStandardItem(mainStruct.subStruct.subValue2));
subStructItem->appendRow(subValue2Item);
}
structures.h
// structures.h
#ifndef STRUCTURES_H
#define STRUCTURES_H
#include <QString>
struct SubStruct {
int subValue1;
QString subValue2;
};
struct MainStruct {
int mainValue1;
QString mainValue2;
SubStruct subStruct;
};
#endif // STRUCTURES_H
main.cpp
// main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
原文地址:https://blog.csdn.net/qq_27741499/article/details/144352863
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!