QHeaderView 表头设置QWidget控件

(恶心的需求)表头要求特殊的字符串(有下标的那种)。本来去掉了表头,将表格的第一行作为表头,这样就可以在表格上添加QLabel控件实现。

这样的弊端就是没有了表头的鼠标拖动的功能。看到QHeaderView有setIndexWidget ( const QModelIndex & index, QWidget * widget )这个函数,所以采用这个方式。

效果如下:

QHeaderView 表头设置QWidget控件_第1张图片

代码如下:

QStringList headherlist;
headherlist << "abc" << "dfg" << "psd" << "jkk";
headherlist.clear();
headherlist << "" << "" << "" << "";
QHeaderView *hview = ui.tableWidget->horizontalHeader();
ui.tableWidget->setColumnCount(headherlist.count());
ui.tableWidget->setHorizontalHeaderLabels(headherlist);

QAbstractItemModel *itemmode = hview->model();

int itemwidth = 98;
int mvw = hview->sectionPosition(0);
QLabel *label = new QLabel(hview);
label->setText("ppp");
label->setAlignment(Qt::AlignCenter);
hview->setIndexWidget(itemmode->index(0,0),label);
label->move(mvw,0);
label->setFixedWidth(itemwidth);
m_headerlabellist << label;


mvw = hview->sectionPosition(1);
label = new QLabel(hview);
label->setText("

R15

"); label->setAlignment(Qt::AlignCenter); hview->setIndexWidget(itemmode->index(0,1),label); label->move(mvw,0); m_headerlabellist << label; mvw = hview->sectionPosition(2); label = new QLabel(hview); label->setText("

R30

"); label->setAlignment(Qt::AlignCenter); hview->setIndexWidget(itemmode->index(0,2),label); label->move(mvw,0); m_headerlabellist << label; //实现拖动功能 connect(hview,SIGNAL(sectionResized ( int , int, int  )),this,SLOT(slots_sectionResized(int,int,int))); //对应的槽函数 void headerviewtest::slots_sectionResized( int logicalIndex, int oldSize, int newSize ) { //方式1 QAbstractItemModel *itemmode = ui.tableWidget->horizontalHeader()->model(); QWidget *w = ui.tableWidget->horizontalHeader()->indexWidget(itemmode->index(0,logicalIndex)); if (w) { w->setFixedWidth(newSize); } for (int i = logicalIndex+1 ; i < itemmode->columnCount(); ++i) { QWidget *w = ui.tableWidget->horizontalHeader()->indexWidget(itemmode->index(0,i)); QLabel *label = qobject_cast(w); if (NULL==w) continue; if (label) qDebug() << ui.tableWidget->horizontalHeader()->sectionPosition(i) << " "<< label->text() << " " ; w->move(ui.tableWidget->horizontalHeader()->sectionPosition(i) -2,0); } /* //方式2 。方式1在一个工程里面不好用,所以才有方式2 if (m_headerlabellist.count() < logicalIndex) return; m_headerlabellist.at(logicalIndex)->setFixedWidth(newSize-4); for (int i = logicalIndex+1 ; i < m_headerlabellist.count(); ++i) { QLabel *w = m_headerlabellist.at(i); if (NULL==w)continue; w->move(ui.tableWidget->horizontalHeader()->sectionPosition(i) -2,0); } */ }

你可能感兴趣的:(Qt)