QT 实现自定义树状导航栏

一、介绍

未经允许,禁止转载!

1.使用技术

Qt包含一组使用模型/视图结构的类,可以用来管理数据并呈现给用户。这种体系结构引入的分离使开发人员更灵活地定制项目,并且提供了一个标准模型的接口,以允许广泛范围的数据源被使用到到现有的视图中。
模型 - 视图 - 控制器(MVC)是一种设计模式,由三类对象组成:
模型:应用程序对象。
视图:屏幕演示。
控制器:定义了用户界面响应用户输入的方式
在这里插入图片描述
Qt把视图和控制器组合在一起,从而形成模型/视图结构。模型直接与数据进行通信,并为视图和委托提供访问数据的接口。

2.效果

展开前:
在这里插入图片描述
展开后:

在这里插入图片描述

传送门(项目源码)

二、实现(重要代码都已加注释)

1.CNavModel模型类

头文件:

#ifndef CNAVMODEL_H
#define CNAVMODEL_H

#include <QAbstractListModel>
#include <QList>
#include <QVector>

class CNavModel : public QAbstractListModel
{
    
    
    Q_OBJECT
public:
    struct TreeNode
    {
    
    
        QString qsLableName;
        int nLevel;
        bool collapse;
        int nIndex;
        QList<TreeNode* > listChildren;
    };

    struct ListNode
    {
    
    
        QString qsLabelName;
        TreeNode* pTreeNode;
    };

public:
    explicit CNavModel(QObject *parent = nullptr);
    ~CNavModel();
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

public:
    void ReadConfig(QString qsPath);    //读取导航栏节点配置文件
    void Refresh(); //刷新模型,我这里没有用到

public slots:
    void Collapse(const QModelIndex& index);    //节点展开、收缩槽函数

private:
    void RefreshList();     //刷新当前界面显示的节点

private:
    QVector<TreeNode*>  m_vecTreeNode;      //用于存储对应关系
    QVector<ListNode>   m_vecListNode;      //存储所有的节点
};

#endif // CNAVMODEL_H

实现:

#include "CNavModel.h"
#include <QFile>
#include <QDomDocument>
#include <QDebug>

CNavModel::CNavModel(QObject *parent)
    : QAbstractListModel(parent)
{
    
    
}

CNavModel::~CNavModel()
{
    
    

    QVector<TreeNode*>  m_vecTreeNode;      
    QVector<ListNode>   m_vecListNode;      
    for(QVector<TreeNode*>::iterator it = m_vecTreeNode.begin(); it != m_vecTreeNode.end(); it++)
    {
    
    
        if((*it)->listChildren.size())
        {
    
    
            for (QList<TreeNode*>::iterator itChild = (*it)->listChildren.begin(); itChild != (*it)->listChildren.end(); it++)
                delete (*itChild);
        }
        delete (*it);
    }

    m_vecListNode.clear();
    m_vecTreeNode.clear();
}

int CNavModel::rowCount(const QModelIndex &parent) const	//返回行数
{
    
    
    return m_vecListNode.size();
}

QVariant CNavModel::data(const QModelIndex &index, int role) const
{
    
    
    if ( !index.isValid() )
        return QVariant();

    if ( index.row() >= m_vecListNode.size() || index.row() < 0 )
        return QVariant();

    if ( role == Qt::DisplayRole )      //显示文字
        return m_vecListNode[index.row()].qsLabelName;
    else if ( role == Qt::UserRole )    //用户定义起始位置
        return QVariant::fromValue((void*)m_vecListNode[index.row()].pTreeNode);

    return QVariant();
}

void CNavModel::ReadConfig(QString qsPath)
{
    
    
    QFile xmlFile(qsPath);
    if(!xmlFile.open(QFile::ReadOnly | QFile::Text))
        return;

    QDomDocument docXml;
    QString error;
    if(!docXml.setContent(&xmlFile, false, &error))
    {
    
    
        xmlFile.close();
        return;
    }

    QDomElement xmlRoot = docXml.documentElement(); //返回根节点
    QDomNode domNode = xmlRoot.firstChild(); //获取子节点,一级节点
    while (!domNode.isNull())
    {
    
    
        if(domNode.isElement())
        {
    
    
            QDomElement domElement = domNode.toElement();   //一级节点
            TreeNode* pTreeNode = new TreeNode;

            pTreeNode->qsLableName = domElement.attribute("lable");//获取一级节点的lable
            pTreeNode->nLevel = 1;  //标志一级节点
            pTreeNode->collapse =  domElement.attribute("collapse").toInt(); //标志是否展开
            pTreeNode->nIndex = domElement.attribute("index").toInt();  //获取标志

            QDomNodeList list = domElement.childNodes();    //获取二级节点
            for(int i = 0; i < list.count(); i++)
            {
    
    
                QDomElement secNodeInfo = list.at(i).toElement();
                TreeNode* pSecNode = new TreeNode;
                pSecNode->qsLableName = secNodeInfo.attribute("lable");
                pSecNode->nLevel = 2;
                pSecNode->nIndex = secNodeInfo.attribute("index").toInt();
                pTreeNode->collapse = false;
                pTreeNode->listChildren.push_back(pSecNode);
            }
            m_vecTreeNode.push_back(pTreeNode);
        }
        domNode = domNode.nextSibling();    //下一一级节点
    }

    xmlFile.close();
    RefreshList();  //刷新界面标题栏展示数据
    beginInsertRows(QModelIndex(), 0, m_vecListNode.size());    //插入所有节点
    endInsertRows(); //结束插入
}

void CNavModel::RefreshList()
{
    
    
    m_vecListNode.clear();
    for(QVector<TreeNode*>::iterator it = m_vecTreeNode.begin(); it != m_vecTreeNode.end(); it++)
    {
    
    
        //一级节点
        ListNode node;
        node.qsLabelName = (*it)->qsLableName;
        node.pTreeNode = *it;
        m_vecListNode.push_back(node);

        if(!(*it)->collapse) //如果一级节点未展开,则插入下一一级节点
            continue;

        for(QList<TreeNode*>::iterator child = (*it)->listChildren.begin(); child != (*it)->listChildren.end(); child++)
        {
    
    
            ListNode node;
            node.qsLabelName = (*child)->qsLableName;
            node.pTreeNode = *child;
            m_vecListNode.push_back(node);
        }
    }
}

void CNavModel::Collapse(const QModelIndex& index)
{
    
    
    TreeNode* pTreeNode = m_vecListNode[index.row()].pTreeNode; //获取当前点击节点
    if(pTreeNode->listChildren.size() == 0) //如果该节点没有子节点 则返回
        return;

    pTreeNode->collapse = !pTreeNode->collapse; //刷新是否展开标志

    if(!pTreeNode->collapse)    //如果是不展开,即为展开变成合并,移除合并的
    {
    
    
        beginRemoveRows(QModelIndex(), index.row() + 1, pTreeNode->listChildren.size()); //默认起始节点为最初节点
        endRemoveRows();
    }
    else {
    
    
        beginInsertRows(QModelIndex(), index.row() + 1, pTreeNode->listChildren.size());
        endInsertRows();
    }
    RefreshList(); //更新界面显示节点数据
}

void CNavModel::Refresh()
{
    
    
    RefreshList();
    beginResetModel();
    endResetModel();
}

2.视图

这里采用的是QListView视图进行列表显示,用户可以进行自行更改视图样式
头文件

#ifndef CNAVVIEW_H
#define CNAVVIEW_H

#include <QObject>
#include <QListView>

class CNavView : public QListView
{
    
    
    Q_OBJECT

public:
    CNavView(QWidget *parent);
    ~CNavView();
};

#endif // CNAVVIEW_H

实现:这里只修改了背景色等

#include "CNavView.h"
#include <QColor>

CNavView::CNavView(QWidget *parent) : QListView (parent)
{
    
    
    setStyleSheet(
        QString(
        "QListView{background-color:%1;"
        "border:0px solid %2;"
        "border-right-width:1px;}")
        .arg("239, 241, 250")
        .arg("214, 216, 224"));
}

CNavView::~CNavView()
{
    
    

}

3.委托

引入委托的目的:项目数据显示和自定义编辑。
头文件:

#ifndef CNAVDELEGATE_H
#define CNAVDELEGATE_H

#include <QObject>
#include <QStyledItemDelegate>

class CNavDelegate : public QStyledItemDelegate
{
    
    
    Q_OBJECT
public:
    CNavDelegate(QObject* parent);
    ~CNavDelegate();

public:
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

    void SetPending(bool pending) {
    
     m_pending = pending; }

private:
    QString GetImagePath(int nIndex) const;

private:
    bool m_pending;
};

#endif // CNAVDELEGATE_H

实现:

#include "CNavDelegate.h"
#include "CNavModel.h"
#include <QPainter>
#include <QColor>

CNavDelegate::CNavDelegate(QObject *parent)
    :QStyledItemDelegate(parent)
    , m_pending(false)
{
    
    

}

CNavDelegate::~CNavDelegate()
{
    
    

}

QSize CNavDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    
    
    CNavModel::TreeNode* pTreeNode = (CNavModel::TreeNode*)index.data(Qt::UserRole).value<void*>();
    if(pTreeNode->nLevel == 1)
        return QSize(50, 45);
    else
        return QSize(50, 28);
}

void CNavDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    
    
    CNavModel::TreeNode* pTreeNode = (CNavModel::TreeNode*)index.data(Qt::UserRole).value<void*>();
    painter->setRenderHint(QPainter::Antialiasing); //防走样

    //根据绘制时提供的信息进行背景色绘制
    if ( option.state & QStyle::State_Selected )
    {
    
    
        painter->fillRect(option.rect, QColor(133, 153, 216));
    }
    else if ( option.state & QStyle::State_MouseOver )
    {
    
    
        painter->fillRect(option.rect, QColor(209, 216, 240));
    }
    else
    {
    
    
        if ( pTreeNode->nLevel == 1 )
            painter->fillRect(option.rect, QColor(247, 249, 255));
        else
            painter->fillRect(option.rect, QColor(239, 241, 250));
    }

    //添加图片
    if(pTreeNode->listChildren.size() != 0)
    {
    
    
        QString qsImagePath;
        if(!pTreeNode->collapse)
        {
    
    
            if ( option.state & QStyle::State_Selected )
                qsImagePath = ":/image/unexpand_selected.png";
            else
                qsImagePath = ":/image/unexpand_normal.png";
        }
        else {
    
    
            if ( option.state & QStyle::State_Selected )
                qsImagePath = ":/image/expand_selected.png";
            else
                qsImagePath = ":/image/expand_normal.png";
        }

        //设置图片大小
        QPixmap img(qsImagePath);
        QRect targetRect = option.rect;
        targetRect.setWidth(16);
        targetRect.setHeight(16);

        //设置图片坐标
        QPoint c = option.rect.center();
        c.setX(8);
        targetRect.moveCenter(c);

        //将图片放到对应位置
        painter->drawPixmap(targetRect, qsImagePath, img.rect());
    }
    else {
    
    
        QString qsPath = GetImagePath(pTreeNode->nIndex);
        if(qsPath.size())
        {
    
    
            QPixmap img(qsPath);
            QRect targetRect = option.rect;
            targetRect.setWidth(16);
            targetRect.setHeight(16);

            //设置图片坐标
            QPoint c = option.rect.center();
            c.setX(12);
            targetRect.moveCenter(c);

            //将图片放到对应位置
            painter->drawPixmap(targetRect, qsPath, img.rect());
        }
    }

    //添加文字
    QPen textPen( option.state & QStyle::State_Selected ? QColor(255, 255, 255) : QColor(58, 58, 58));
    painter->setPen(textPen);

    int margin = 25;

    if ( pTreeNode->nLevel == 2 )
        margin = 45;

    QRect rect = option.rect;
    rect.setWidth(rect.width() - margin);
    rect.setX(rect.x() + margin);

    QFont normalFont("Microsoft Yahei", 9);
    painter->setFont(normalFont);
    painter->drawText(rect, Qt::AlignLeft | Qt::AlignVCenter, index.data(Qt::DisplayRole).toString() );

    //在每一行下方划线
    QPen linePen(QColor(214, 216, 224));
    linePen.setWidth(1);
    painter->setPen(linePen);

    if ( pTreeNode->nLevel == 1
        || (pTreeNode->nLevel == 2 ) )
    {
    
    
        painter->drawLine(
            QPointF(option.rect.x(), option.rect.y()+option.rect.height()-1),
            QPointF(option.rect.x() + option.rect.width(), option.rect.y()+option.rect.height()-1));
    }
}

QString CNavDelegate::GetImagePath(int nIndex) const
{
    
    
    switch (nIndex)
    {
    
    
    case 1:
        return QString();
    case 13:
        return QString(":/image/Purchase.png");
    case 16:
        return QString(":/image/Tasklist.png");
    case 17:
        return QString(":/image/Trendchart.png");
    default:
        return QString();
    }
}

4.使用:

void CMainFrm::SetNavigationBar()
{
    
    
    CNavModel* pNavModel = new CNavModel(this);
    CNavDelegate* pDelegate = new CNavDelegate(this);
    pNavModel->ReadConfig(QCoreApplication::applicationDirPath() += "/config/navigation.xml");
    ui->listView->setModel(pNavModel);
    ui->listView->setItemDelegate(pDelegate);
    connect(ui->listView, SIGNAL(doubleClicked(const QModelIndex &)), pNavModel, SLOT(Collapse(const QModelIndex &)));
}

项目源码:

传送门
各位观众老爷,如果觉得有点帮助请点个赞,给咱涨涨积分

猜你喜欢

转载自blog.csdn.net/qq_42956179/article/details/110817651