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. 如要轉載,請原文轉載,如在轉載時修改本文,請事先告知,謝絕在轉載時經過修改本文達到有利於轉載者的目的。

相關文章
相關標籤/搜索