Qt实现表格树控件-支持多级表头

原文连接:Qt实现表格树控件-支持多级表头浏览器

1、概述

以前写过一篇关于表格控件多级表头的文章,喜欢的话能够参考Qt实现表格控件-支持多级列表头、多级行表头、单元格合并、字体设置等。今天这篇文章带来了比表格更加复杂的控件-树控件多级表头实现。数据结构

在Qt中,表格控件包含有水平和垂直表头,可是常规使用模式下都是只能实现一级表头,而树控件虽然包含有了branch分支,这也间接的削弱了他自身的表头功能,细心的同窗可能会发现Qt自带的QTreeView树控件只包含有水平表头,没有了垂直表头。app

既然Qt自带的控件中没有这个功能,那么咱们只能本身去实现了。ide

要实现多级表头功能方式也多种多样,以前就看到过几篇关于实现多级表头的文章,整体能够分为以下两种方式函数

  1. 表头使用一个表格来模拟
  2. 经过给表头自定义Model

今天这篇文章咱们是经过方式2来实现多级表头。如效果图所示,实现的是一个树控件的多级表头,而且他还包含了垂直列头,实现这个控件所须要完成的代码量仍是比较多的。本篇文章能够算做是一个开头吧,后续会逐步把关键功能的实现方式分享出来。布局

2、效果展现

3、实现方式

本篇文章中的控件看起来是一个树控件,可是他又具有了表格控件该有的一些特性,好比垂直表头、多级水平表头等等。要实现这样的树控件,咱们有两个大的方向能够去考虑测试

  1. 重写表格控件,实现branch
  2. 表格控件+树控件

方式1重写表格控件实行branch的工做量是比较大的,并且须要把Qt本来的代码迁出来,工做量会比加大,我的选择了发你。字体

方式2是表格控件+树控件的实现方式,说白了就是表格控件提供水平和垂直表头,树控件提供内容展现,听起来好像没毛病,那么还等什么,直接干呗。this

既然大方向定了,那么接下来可能就是一些细节问题的肯定。

  1. 多级水平表头
  2. 垂直列头拖拽时,实现树控件行高同步变更
  3. 自绘branch

以上三个问题都是实现表格树控件时遇到的一些比较棘手的问题,后续会分别经过单独的文章来进行讲解,今天这篇文章也是咱们的第一讲,怎么实现水平多级表头

4、多级表头

第一节咱们也说了,实现多级表头咱们使用重写model的方式来实现,接下来就是贴代码的时候。

一、数据源

常常重写model的同窗对以下代码应该不陌生,对于继承自QAbstractItemModel的数据源确定是须要重写该类的全部纯虚方法,包括全部间接父类的纯虚方法。

除此以外自定义model应该还须要提供一个能够合并单元格的方法,为何呢?由于咱们多级表头须要。好比说咱们一级表头下有3个二级表头,那这就说明一级表头合并了3列,使得自己的3列数据变成一列。

class HHeaderModel : public QAbstractItemModel
{
    struct ModelData //模型数据结构
    {
        QString text;

        ModelData() : text("")
        {
        }
    };

    Q_OBJECT

public:
    HHeaderModel(QObject * parent = 0);
    ~HHeaderModel();

public:
    void setItem(int row, int col, const QString & text);

    QString item(int row, int col);

    void setSpan(int firstRow, int firstColumn, int rowSpanCount, int columnSpanCount);
    const CellSpan& getSpan(int row, int column);

public:
    virtual QModelIndex index(int row, int column, const QModelIndex & parent) const override;
    virtual QModelIndex parent(const QModelIndex & child) const override;
    virtual int rowCount(const QModelIndex & parent) const override;
    virtual int columnCount(const QModelIndex & parent) const override;
    virtual QVariant data(const QModelIndex & index, int role) const override;
    virtual Qt::ItemFlags flags(const QModelIndex & index) const override;
    virtual bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) override;
    virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const override;

private:
    //找到对应的模型数据
    ModelData * modelData(const QModelIndex & index) const;

private:
    //key rowNo,  key colNo
    QMap<int, QMap<int, ModelData *> > m_modelDataMap;
    int m_iMaxCol;

    CellSpan m_InvalidCellSpan;
    QList<CellSpan> m_cellSpanList;
};

以上即是model的头文件声明,其中重写父类的虚方法这里就不作过多说明,和平时重写其余数据源没有区别,这里多了重点说明下setSpan接口。

void HHeaderModel::setSpan(int firstRow, int firstColumn, int rowSpanCount, int columnSpanCount)
{
    for (int row = firstRow; row < firstRow + rowSpanCount; ++row)
    {
        for (int col = firstColumn; col < firstColumn + columnSpanCount; ++col)
        {
            m_cellSpanList.append(CellSpan(row, col, rowSpanCount, columnSpanCount, firstRow, firstColumn));
        }
    }
}

const CellSpan& HHeaderModel::getSpan(int row, int column)
{
    for (QList<CellSpan>::const_iterator iter = m_cellSpanList.begin(); iter != m_cellSpanList.end(); ++iter)
    {
        if ((*iter).curRow == row && (*iter).curCol == column)
        {
            return *iter;
        }
    }

    return m_InvalidCellSpan;
}

setSpan接口存储了哪些列或者行被合并了,在绘制表格头时咱们也能够根据这些信息来计算绘制的大小和位置。

二、表格

数据源介绍完,接下来看看表头视图类,这个类相对Model来讲会复杂不少,主要也是根据Model中存储的合并信息来进行绘制。

因为这个类代码比价多,这里我就不贴头文件声明了,下面仍是主要介绍下关键函数

a、paintEvent绘制函数

void HHeaderView::paintEvent(QPaintEvent * event)
{
    QPainter painter(viewport());
    QMultiMap<int, int> rowSpanList;

    int cnt = count();
    int curRow, curCol;
    
    HHeaderModel * model = qobject_cast<HHeaderModel *>(this->model());
    for (int row = 0; row < model->rowCount(QModelIndex()); ++row)
    {
        for (int col = 0; col < model->columnCount(QModelIndex()); ++col)
        {
            curRow = row;
            curCol = col;

            QStyleOptionViewItemV4 opt = viewOptions();

            QStyleOptionHeader header_opt;
            initStyleOption(&header_opt);

            header_opt.textAlignment = Qt::AlignCenter;
            // header_opt.icon = QIcon("./Resources/logo.ico");
            QFont fnt;
            fnt.setBold(true);
            header_opt.fontMetrics = QFontMetrics(fnt);

            opt.fontMetrics = QFontMetrics(fnt);
            QSize size = style()->sizeFromContents(QStyle::CT_HeaderSection, &header_opt, QSize(), this);

            // size.setHeight(25);
            header_opt.position = QStyleOptionHeader::Middle;

            //判断当前行是否处于鼠标悬停状态
            if (m_hoverIndex == model->index(row, col, QModelIndex()))
            {
                header_opt.state |= QStyle::State_MouseOver;
                // header_opt.state |= QStyle::State_Active;
            }

            opt.text = model->item(row, col);
            header_opt.text = model->item(row, col);

            CellSpan span = model->getSpan(row, col);

            int rowSpan = span.rowSpan;
            int columnSpan = span.colSpan;

            if (columnSpan > 1 && rowSpan > 1)
            {
                //单元格跨越多列和多行, 不支持,改成多行1列
                continue;
                /*header_opt.rect = QRect(sectionViewportPosition(logicalIndex(col)), row * size.height(), sectionSizes(col, columnSpan), rowSpan * size.height());
                opt.rect = header_opt.rect;
                col += columnSpan - 1; */
            }
            else if (columnSpan > 1)//单元格跨越多列
            {
                header_opt.rect = QRect(sectionViewportPosition(logicalIndex(col)), row * size.height(), sectionSizes(col, columnSpan), size.height());
                opt.rect = header_opt.rect;
                col += columnSpan - 1;
            }
            else if (rowSpan > 1)//单元格跨越多行
            {
                header_opt.rect = QRect(sectionViewportPosition(logicalIndex(col)), row * size.height(), sectionSize(logicalIndex(col)), size.height() * rowSpan);
                opt.rect = header_opt.rect;
                for (int i = row + 1; i <= rowSpan - 1; ++i)
                {
                    rowSpanList.insert(i, col);
                }
            }
            else
            {
                //正常的单元格
                header_opt.rect = QRect(sectionViewportPosition(logicalIndex(col)), row * size.height(), sectionSize(logicalIndex(col)), size.height());
                opt.rect = header_opt.rect;
            }

            opt.state = header_opt.state;

            //opt.displayAlignment = Qt::AlignCenter;

            //opt.icon = QIcon("./Resources/logo.ico");
            //opt.backgroundBrush = QBrush(QColor(255, 0, 0));
            QMultiMap<int, int>::iterator it = rowSpanList.find(curRow, curCol);
            if (it == rowSpanList.end())
            {
                //保存当前item的矩形
                m_itemRectMap[curRow][curCol] = header_opt.rect;
                itemDelegate()->paint(&painter, opt, model->index(curRow, curCol, QModelIndex()));

                painter.setPen(QColor("#e5e5e5"));
                painter.drawLine(opt.rect.bottomLeft(), opt.rect.bottomRight());
            }
            else
            {
                //若是是跨越多行1列的状况,采用默认的paint
            }
        }
    }

    //painter.drawLine(viewport()->rect().bottomLeft(), viewport()->rect().bottomRight());
}

b、列宽发生变化

void HHeaderView::onSectionResized(int logicalIndex, int oldSize, int newSize)
{
    if (0 == newSize)
    {
        //过滤掉隐藏列致使的resize
        viewport()->update();
        return;
    }

    static bool selfEmitFlag = false;
    if (selfEmitFlag)
    {
        return;
    }

    int minWidth = 99999;
    QFontMetrics metrics(font());
    //获取这列上最小的字体宽度,移动的长度不能大于最小的字体宽度
    HHeaderModel * model = qobject_cast<HHeaderModel *> (this->model());
    for (int i = 0; i < model->rowCount(QModelIndex()); ++i)
    {
        QString text = model->item(i, logicalIndex);
        if (text.isEmpty())
            continue;

        int textWidth = metrics.width(text);
        if (minWidth > textWidth)
        {
            minWidth = textWidth;
        }
    }

    if (newSize < minWidth)
    {
        selfEmitFlag = true;
        resizeSection(logicalIndex, oldSize);
        selfEmitFlag = false;
    }

    viewport()->update();
}

三、QStyledItemDelegate绘制代理

既然说到了自绘,那么有必要说下Qt自绘相关的一些东西。

a、paintEvent

paintEvent是QWidget提供的自绘函数,当界面刷新时该接口就会被调用。

b、复杂控件自绘

对于一些比较复杂的控件为了达到更好的定制型,Qt把paintEvent函数中的绘制过程进行了更为详细的切割,也可让咱们进行布局的重写。

好比今天说到的树控件,当paintEvent函数调用时,其实内部真正进行绘制的是以下3个函数,重写以下三个函数能够为咱们带来更友好的定制性,而且很大程度上减轻了咱们本身去实现的风险。

virtual void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const
virtual void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
void drawTree(QPainter *painter, const QRegion &region) const

c、QStyledItemDelegate绘制代理

为了更好的代码管理和接口抽象,Qt在处理一些超级变态的控件时提供了绘制代理这个类,即便在一些力度很小的绘制函数中依然是调用的绘制代理去绘图。

恰好咱们今天说的这个表头绘制就是如此。以下代码所示,是一部分的HHeaderItemDelegate::paint函数展现,主要是针对表头排序进行了定制。

void HHeaderItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    int row = index.row();
    int col = index.column();

    const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

    QStyleOptionHeader header_opt;
    header_opt.rect = option.rect;
    header_opt.position = QStyleOptionHeader::Middle;
    header_opt.textAlignment = Qt::AlignCenter;

    header_opt.state = option.state;
    //header_opt.state |= QStyle::State_HasFocus;//QStyle::State_Enabled | QStyle::State_Horizontal | QStyle::State_None | QStyle::State_Raised;


    if (HHeaderView::instance->isItemPress(row, col))
    {
        header_opt.state |= QStyle::State_Sunken; //按钮按下效果
    }

    // if ((QApplication::mouseButtons() && (Qt::LeftButton || Qt::RightButton)))
    //             header_opt.state |= QStyle::State_Sunken;

    painter->save();
    QApplication::style()->drawControl(QStyle::CE_Header, &header_opt, painter);
    painter->restore();
}

5、测试代码

把须要合并的列和行进行合并,便可达到多级表头的效果,以下是设置表格model合并接口展现。

horizontalHeaderModel->setSpan(0, 0, 1, 4);
horizontalHeaderModel->setSpan(0, 4, 1, 3);
horizontalHeaderModel->setSpan(0, 7, 1, 3);

horizontalHeaderModel->setSpan(0, 10, 2, 1);
horizontalHeaderModel->setSpan(0, 11, 2, 1); //不支持跨越多行多列的状况
}

model设置完毕后只要把Model设置给QHeaderView类便可。

6、相关文章

值得一看的优秀文章:

  1. 财联社-产品展现
  2. 广联达-产品展现
  3. Qt定制控件列表
  4. 牛逼哄哄的Qt库

  1. Qt实现表格控件-支持多级列表头、多级行表头、单元格合并、字体设置等

  2. Qt高仿Excel表格组件-支持冻结列、冻结行、内容自适应和合并单元格

  3. 属性浏览器控件QtTreePropertyBrowser编译成动态库(设计师插件)

  4. 超级实用的属性浏览器控件--QtTreePropertyBrowser

  5. Qt之表格控件蚂蚁线

  6. QRowTable表格控件-支持hover整行、checked整行、指定列排序等





若是您以为文章不错,不妨给个 打赏,写做不易,感谢各位的支持。您的支持是我最大的动力,谢谢!!!














很重要--转载声明

  1. 本站文章无特别说明,皆为原创,版权全部,转载时请用连接的方式,给出原文出处。同时写上原做者:朝十晚八 or Twowords

  2. 如要转载,请原文转载,如在转载时修改本文,请事先告知,谢绝在转载时经过修改本文达到有利于转载者的目的。

相关文章
相关标签/搜索