QHeaderView 表头设置QWidget控件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chyuanrufeng/article/details/80834514
(恶心的需求)表头要求特殊的字符串(有下标的那种)。本来去掉了表头,将表格的第一行作为表头,这样就可以在表格上添加QLabel控件实现。

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

效果如下:

代码如下:

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("<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">R<span style=\" vertical-align:sub;\">15</span></p>");
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("<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">R<span style=\" vertical-align:sub;\">30</span></p>");
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<QLabel *>(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);
}
*/
}

猜你喜欢

转载自blog.csdn.net/chyuanrufeng/article/details/80834514
今日推荐