QTableView插入QCheckBox复选框

本文介绍了如何在QTableView中插入QCheckBox,通过展示效果图和提供源码,展示了具体实现过程。源码下载链接已给出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图在这里插入图片描述

源码

#ifndef CCHECKBOXMODEL_H
#define CCHECKBOXMODEL_H

#include <QAbstractTableModel>
#include <QStyledItemDelegate>
#include <QEvent>
#include <QHeaderView>
#include <QPainter>


class TableHeaderView :public QHeaderView
{
   
	Q_OBJECT
public:
	TableHeaderView(Qt::Orientation orientation, QWidget *parent);
	~TableHeaderView();

protected:
	void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
	bool event(QEvent *e) Q_DECL_OVERRIDE;
	void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
	void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;

	public slots:
	void onStateChanged(int state);

signals:
	void stateChanged(int state);

private:
	bool m_bPressed;
	bool m_bChecked;
	bool m_bTristate;
	bool m_bNoChange;
	bool m_bMoving;
};


class CheckBoxDelegate :public QStyledItemDelegate
{
   
	Q_OBJECT
public:
    CheckBoxDelegate(QObject *parent);
    ~CheckBoxDelegate();
    // painting
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

protected:
    bool editorEvent(QEvent *event, QAbstractItemModel *model,
                     const QStyleOptionViewItem &option, const QModelIndex &index);
};



#endif // TABLE_MODEL_H

#include "ccheckboxmodel.h"
#include <QCheckBox>
#include <QApplication>
#include <QMouseEvent>
#include <qmessagebox.h>

#ifdef _MSC_VER
#pragma execution_character_set("utf-8")
#endif

#define CHECK_BOX_COLUMN 0
TableHeaderView::TableHeaderView(Qt::Orientation orientation, QWidget *parent)
	: QHeaderView(orientation, parent),
	m_bPressed(false),
	m_bChecked(false),
	m_bTristate(false),
	m_bNoChange(false),
	m_bMoving(false)
	
{
   	
    setSectionsClickable(true); // 响应鼠标
}

TableHeaderView::~TableHeaderView()
{
   

}

// 槽函数,用于更新复选框状态
void TableHeaderView::onStateChanged(int state)
{
   
	if (state == Qt::PartiallyChecked) {
   
		m_bTristate = true;
		m_bNoChange = true;
	}
	else {
   
		m_bNoChange = false;
	}

	m_bChecked = (state != Qt::Unchecked);
	update();
}

// 绘制复选框
void TableHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
   
	painter->save();
	QHeaderView::paintSection(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值