QTableView表格控件默认是不支持插入QComboBox、QPushButton、QCheckBox或者是多种复杂控件组成的列头。在实际开发过程中,表格控件通常是需要进行定制化。我们以列头中插入QComboBox为例实现一个简单的自定义列头。
1、实现思路
用一个QWidget替换掉原列头绘制位置。
2、实现方式
继承QHeaderView实现自己的表头类CustomHeader,重写paintSection函数。在CustomHeader构造中创建好自己想要的QWidget,在CustomHeader绘制列头区域时用自己的Widget覆盖掉原区域。
CustomHeader::CustomHeader(Qt::Orientation orientation, QWidget *parent)
: QHeaderView(orientation, parent)
{
// 创建一个QWidget
m_pFirstCol = new QWidget((QWidget*)this);
// 添加布局
QHBoxLayout *pLayout = new QHBoxLayout(m_pFirstCol);
pLayout->setContentsMargins(2, 0, 2, 0);
pLayout->setSpacing(4);
// QLabel 用于显示列名
QLabel *pName = new QLabel(m_pFirstCol);
pName->setText("第一列");
pLayout->addWidget(pName);
// 添加一个下拉框
QComboBox *pComboBox = new QComboBox(m_pFirstCol);
pLayout->addWidget(pComboBox);
}