QHeaderView支持复选框

lxg / 2023-08-17 / 原文

点击查看代码
class CustomHeaderView : public QHeaderView
{
	Q_OBJECT
public:
    CustomHeaderView(Qt::Orientation orientation, QWidget* parent = nullptr)
		: QHeaderView(orientation, parent)
	{
		setSectionsClickable(true);
	}

	void setTriState(Qt::CheckState state) {
		triState = state;
		updateSection(0);
	}
void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const override
	{
		painter->save();
		QHeaderView::paintSection(painter, rect, logicalIndex);
		painter->restore();

		if (logicalIndex == 0) {
			QStyleOptionButton option;
			option.initFrom(this);
			option.rect = QRect(rect.x() + 28, rect.y() + 4, 16, 16);
			option.features = QStyleOptionButton::None;
if (triState == Qt::Checked)
				option.state |= QStyle::State_On;
			else if (triState == Qt::PartiallyChecked)
				option.state |= QStyle::State_NoChange;
			else
				option.state |= QStyle::State_Off;

			style()->drawControl(QStyle::CE_CheckBox, &option, painter);
		}
	}
void mousePressEvent(QMouseEvent* event) override
	{
		if (event->button() == Qt::LeftButton) {
			if (logicalIndexAt(event->pos()) == 0) {
				switch (triState) {
				case Qt::Unchecked:
					triState = Qt::Checked;
					break;
				case Qt::Checked:
					triState = Qt::Unchecked;
					break;
					//case Qt::PartiallyChecked:
					//	triState = Qt::Unchecked;
					//	break;
				}
updateSection(0);
				emit checkBoxStateChanged(triState);
			}
		}

		QHeaderView::mousePressEvent(event);
	}

	Qt::CheckState isChecked() const {
		return triState;
	}
signals:
	void checkBoxStateChanged(Qt::CheckState state);

private:
	Qt::CheckState triState = Qt::Unchecked;
};