欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt QHeaderView 表头添加复选框

程序员文章站 2024-02-05 12:52:16
...

参考资料 : https://wiki.qt.io/Technical_FAQ#How_can_I_insert_a_checkbox_into_the_header_of_my_view.3F

http://blog.csdn.net/liang19890820/article/details/50772562

先重写自定义自己的QheaderView类

#include <QtGui>
class MyCheckboxHeader : public QHeaderView
{
	Q_OBJECT
public:
	MyCheckboxHeader(Qt::Orientation orientation, QWidget * parent = 0) : QHeaderView(orientation, parent), isOn(false)
	{}
	void cancelSelectAll()
	{
		isOn = false;
		emit signalStateTrange(isOn);
		this->update();
	}
signals:
	void signalStateTrange(int);
protected:
	void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
	{
		painter->save();
		QHeaderView::paintSection(painter, rect, logicalIndex);
		painter->restore();
		if (logicalIndex == 0)
		{
			QStyleOptionButton option;
			option.rect = QRect(10, 10, 10, 10);
			if (isOn)
				option.state = QStyle::State_On;
			else
				option.state = QStyle::State_Off;
			QCheckBox checkBox;
			option.iconSize = QSize(20, 20);
			option.rect = rect;
			

			style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter, &checkBox);
			//this->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
		}

	}
	void mousePressEvent(QMouseEvent *event)
	{
		
		if (event->button() == Qt::LeftButton) {
			int index = logicalIndexAt(event->pos());
			if (index == 0)
			{
				if (isOn)
					isOn = false;
				else
					isOn = true;
			}
			emit signalStateTrange(isOn);
		}
			
		this->update();
		QHeaderView::mousePressEvent(event);
	}
private:
	bool isOn;
};
int main(int argc, char **argv)//QTableWidget 实现此种表
{
  QApplication app(argc, argv);
  QTableWidget table;
  table.setRowCount(4);
  table.setColumnCount(3);
MyCheckboxHeader *myHeader = new MyCheckboxHeader(Qt::Horizontal, &table);
  table.setHorizontalHeader(myHeader);  
  table.show();}

//笔者用的是QTableview(model+view)模型数据形式的表 表头列已经在model类的headerdata函数定义无需改动 如下调用即可

QTableView *m_logTable = new QTableView();
	MyCheckboxHeader *myHeader = new MyCheckboxHeader(Qt::Horizontal, m_logTable);m_logTable->resizeColumnsToContents();m_logTable->setHorizontalHeader(myHeader);m_logTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//connect(myHeader, SIGNAL(signalStateTrange(int)), this, SLOT(slotsSelectAll(int))); checkbox触发信号槽
效果:Qt QHeaderView 表头添加复选框