1. 程式人生 > >Qt實現表格樹控制元件-支援多級表頭

Qt實現表格樹控制元件-支援多級表頭

目錄

  • 一、概述
  • 二、效果展示
  • 三、實現方式
  • 四、多級表頭
    • 1、資料來源
    • 2、表格
    • 3、QStyledItemDelegate繪製代理
  • 五、測試程式碼
  • 六、相關文章

原文連結:Qt實現表格樹控制元件-支援多級表頭

一、概述

之前寫過一篇關於表格控制元件多級表頭的文章,喜歡的話可以參考Qt實現表格控制元件-支援多級列表頭、多級行表頭、單元格合併、字型設定等。今天這篇文章帶來了比表格更加複雜的控制元件-樹控制元件多級表頭實現。

在Qt中,表格控制元件包含有水平和垂直表頭,但是常規使用模式下都是隻能實現一級表頭,而樹控制元件雖然包含有了branch分支,這也間接的削弱了他自身的表頭功能,細心的同學可能會發現Qt自帶的QTreeView樹控制元件只包含有水平表頭,沒有了垂直表頭。

既然Qt自帶的控制元件中沒有這個功能,那麼我們只能自己去實現了。

要實現多級表頭功能方式也多種多樣,之前就看到過幾篇關於實現多級表頭的文章,總體可以分為如下兩種方式

  1. 表頭使用一個表格來模擬
  2. 通過給表頭自定義Model

今天這篇文章我們是通過方式2來實現多級表頭。如效果圖所示,實現的是一個樹控制元件的多級表頭,並且他還包含了垂直列頭,實現這個控制元件所需要完成的程式碼量還是比較多的。本篇文章可以算作是一個開頭吧,後續會逐步把關鍵功能的實現方式分享出來。

二、效果展示

三、實現方式

本篇文章中的控制元件看起來是一個樹控制元件,但是他又具備了表格控制元件該有的一些特性,比如垂直表頭、多級水平表頭等等。要實現這樣的樹控制元件,我們有兩個大的方向可以去考慮

  1. 重寫表格控制元件,實現branch
  2. 表格控制元件+樹控制元件

方式1重寫表格控制元件實行branch的工作量是比較大的,而且需要把Qt原本的程式碼遷出來,工作量會比加大,個人選擇了發你。

方式2是表格控制元件+樹控制元件的實現方式,說白了就是表格控制元件提供水平和垂直表頭,樹控制元件提供內容展示,聽起來好像沒毛病,那麼還等什麼,直接幹唄。

既然大方向定了,那麼接下來可能就是一些細節問題的確定。

  1. 多級水平表頭
  2. 垂直列頭拖拽時,實現樹控制元件行高同步變動
  3. 自繪branch

以上三個問題都是實現表格樹控制元件時遇到的一些比較棘手的問題,後續會分別通過單獨的文章來進行講解,今天這篇文章也是我們的第一講,怎麼實現水平多級表頭

四、多級表頭

第一節我們也說了,實現多級表頭我們使用重寫model的方式來實現,接下來就是貼程式碼的時候。

1、資料來源

經常重寫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介面儲存了哪些列或者行被合併了,在繪製表格頭時我們也可以根據這些資訊來計算繪製的大小和位置。

2、表格

資料來源介紹完,接下來看看錶頭檢視類,這個類相對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();
}

3、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();
}

五、測試程式碼

把需要合併的列和行進行合併,即可達到多級表頭的效果,如下是設定表格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類即可。

六、相關文章

值得一看的優秀文章:

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