#QTablewidget实现多级表头
#效果图

此方法仅用一个QTablewidget实现了多级表头,不要重写
核心代码如下:
for ( int i = 0; i < ui->tableWidget->columnCount();++i){
if (i == 0){
QWidget *pWidget1 = new QWidget();
QVBoxLayout *pVB1 = new QVBoxLayout();
pVB1->setContentsMargins(0,0,0,0);
pWidget1->setLayout(pVB1);
QLabel *pLab1 = new QLabel("Trance number");
pLab1->setAlignment(Qt::AlignCenter);
pVB1->addWidget(pLab1);
ui->tableWidget->setCellWidget(0,i,pWidget1);
}
else
{
QLabel *pLab2 = new QLabel("trc seq\n in line\n 1 - 4");
pLab2->setAlignment(Qt::AlignCenter);
QComboBox *pCB2 = new QComboBox();
pCB2->addItem("Line Header");
QWidget *pWidget2 = new QWidget();
QVBoxLayout *pVB2 = new QVBoxLayout();
pVB2->setContentsMargins(0,0,0,0);
pVB2->addWidget(pLab2);
pVB2->addWidget(pCB2);
pWidget2->setLayout(pVB2);
ui->tableWidget->setCellWidget(0,i,pWidget2);
}
}
方法原理:去掉Qtablewidget行,列标题,通过上诉方法即可实现。
原因是我们添加的widge全都在表的第一行,也就是现在的第一行就是多级表头,之后如果添加数据
可以从第二行进行添加。切记:当你用ui->tableWidget->rowCount()时需要计算好行号。
因为我们添加数据实际上是从表的第二行开始添加数据的。