在Qt框架中,`QTableWidget`是常用的用于显示二维数据的控件。在一些复杂的用户界面设计中,可能需要对表头进行自定义,例如添加复选框或下拉框,以提供更丰富的交互功能。
在本篇中,我们将深入探讨如何在`QTableWidget`的表头中实现这些自定义功能,以`复选框`为例。
在Qt5中,要实现自定义表头,需要重写`QHeaderView`类,它是`QTableView`和`QTableWidget`的表头部分。以下是一些关键步骤:
1. **创建自定义表头类**:我们需要继承`QHeaderView`并实现自己的逻辑。
创建一个名为`CheckBoxTableHeader`的类
class CheckBoxTableHeader : public QHeaderView {
Q_OBJECT
private:
bool isChecked;
int m_checkColIdx;
public:
CheckBoxTableHeader(int checkColumnIndex, Qt::Orientation orientation, QWidget* parent = 0) : QHeaderView(orientation, parent) {
m_checkColIdx = checkColumnIndex;
isChecked = false;
}
signals:
void checkStausChange(bool);
protected:
void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const;
void mousePressEvent(QMouseEvent* event);
};
2. **添加复选框**:此处以QStyleOptionButton的方式实现,也可以通过添加复选框`QCheckBox`控件的方式实现。
在`CheckBoxTableHeader`的`paintSection`方法中,可以定位复选框的位置,并在画布上绘制它。
void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
painter->save();
QHeaderView::paintSection(painter, rect, logicalIndex);
painter->restore();
if (logicalIndex == m_checkColIdx) {
QStyleOptionButton option;
int width = 10;
for (int i = 0; i < logicalIndex; ++i)
width += sectionSize(i);
option.rect = QRect(2+width, 3, 21, 21); ///此处可以进行修正大小和位置
if (isChecked)
option.state = QStyle::State_On;
else
option.state = QStyle::State_Off;
this->style()->drawControl(QStyle::CE_CheckBox, &option, painter);
}
}
3. **处理点击事件**: 重写`mousePressEvent`, 更新复选框的状态,并同步到数据模型。
void mousePressEvent(QMouseEvent* event) {
if (visualIndexAt(event->pos().x()) == m_checkColIdx)
{
isChecked =!isChecked;
this->updateSection(m_checkColIdx);
emit checkStausChange(isChecked);
}
QHeaderView::mousePressEvent(event);
}
4. **关联到表格**:将创建的`CheckBoxTableHeader`实例设置为`QTableWidget`的水平或垂直表头,
使用`setHorizontalHeader`或`setVerticalHeader`方法。
QTableWidget tableWidget(5, 5);
CheckBoxTableHeader *m_checkHeader = new CheckBoxTableHeader(1, Qt::Horizontal, &tableWidget);
tableWidget.setHorizontalHeader(m_checkHeader);