1.通过c++代码实现model,继承自QAbstractItemModel,代码如下:
①头文件实现如下(CustomTreeModel.h):
#ifndef CUSTOMTREEMODEL_H
#define CUSTOMTREEMODEL_H
#include <QAbstractItemModel>
#include "TreeItem.h"
class CustomTreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit CustomTreeModel(const QString &data="main1\tsub\n child1\tsub\nmain2\tsub2", QObject *parent = 0);
~CustomTreeModel();
QVariant data(const QModelIndex &index, int role) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QHash<int, QByteArray> CustomTreeModel::roleNames() const override;
private:
void setupModelData(const QStringList &lines, TreeItem *parent);
TreeItem *rootItem;
int NAME;
int SUMMARY;
};
#endif // CUSTOMTREEMODEL_H
②源文件实现如下(CustomTreeModel.cpp):
#include "CustomTreeModel.h"
#include <QStringList>
#include <QDebug>
CustomTreeModel::CustomTreeModel(const QString &data, QObject *parent)
: QAbstractItemModel(parent)
{
NAME = Qt::UserRole;
S