Qt實現表格樹控件-支持多級表頭


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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM