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);
}
CustomHeader::~CustomHeader()
{
}
void CustomHeader::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
if (logicalIndex == 0)
{
m_pFirstCol->setGeometry(rect); // 第一列特殊处理
}
else
{
QHeaderView::paintSection(painter, rect, logicalIndex);
}
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
initTable();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initTable()
{
QStandardItemModel *pModel = new QStandardItemModel(ui->tableView);
ui->tableView->setModel(pModel);
CustomHeader *pHeader = new CustomHeader(Qt::Orientation::Horizontal, ui->tableView);
ui->tableView->setHorizontalHeader(pHeader);
QStringList headerList;
headerList << "第一列" << "第二列" << "第三列";
pModel->setHorizontalHeaderLabels(headerList);
}
3、结尾
通过上述方式我们可以给列头自由添加各种类型的控件,比如QPushButton、QCheckBox等等。