QTreeView developed using AbstractItemModel

Purpose: To implement a tree-like tree structure

1. In the example, the definition of MineModel:

class MinevModel: public QAbstractItemModel 
{
    
    
    Q_OBJECT
public:
    MinevModel();
    ~MinevModel();
private:
    virtual QVariant data(const QModelIndex& index, int role) const;
}

2. Implement a tree structure containing only text

In the custom class inherited from AbstractItemModel, rewrite the data function, and when the incoming role is Qt::DisplayRole, just return the corresponding string.

QVariant
MinevModel::data(const QModelIndex& index, int role) const
{
    
    
    if (!index.isValid())
        return QVariant();
    switch (role)
    {
    
    
    case Qt::DisplayRole: // 这里处理了DisplayRole,TreeView的Control端会生成对应的label。
    {
    
    
        return "HelloWorld";
    }
    default:
        break;
    }
     return QVariant();
}

3. Implement a tree structure whose sub-object is a checkbox

In the custom class inherited from AbstractItemModel, rewrite the data function, and when the incoming role is Qt::DisplayRole, return the corresponding string; when the incoming role is Qt::CheckStateRole, return the corresponding QCheckState;

QVariant
MinevModel::data(const QModelIndex& index, int role) const
{
    
    
    if (!index.isValid())
        return QVariant();
    switch (role)
    {
    
    
    case Qt::DisplayRole: // 这里处理了DisplayRole,TreeView的Control端会生成对应的label。
    {
    
    
        return "HelloWorld";
    }
     case Qt::CheckStateRole: // 这里处理了CheckStateRole,TreeView的Control端会生成对应的checkbox。
    {
    
    
        return Qt::Checked;
    }
    default:
        break;
    }
     return QVariant();
}

principle

QTreeView uses the MCV data structure to process the interface and data separately; as long as we implement the model's data function and return the corresponding type of enumeration value (Qt::ItemDataRole), QTreeView will create the corresponding The display (label, checkbox, image, etc.). Regarding my personal understanding of MVC of QTreeView, as shown in the figure below, it only represents my personal opinion. If you have any questions, please give me some advice.
Insert image description here

Guess you like

Origin blog.csdn.net/qq_41841073/article/details/134555716