QHeaderView 表头设置QWidget控件
生活随笔
收集整理的這篇文章主要介紹了
QHeaderView 表头设置QWidget控件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
(惡心的需求)表頭要求特殊的字符串(有下標的那種)。本來去掉了表頭,將表格的第一行作為表頭,這樣就可以在表格上添加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); } */ }總結
以上是生活随笔為你收集整理的QHeaderView 表头设置QWidget控件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ionic开发记账软件《易跟金》
- 下一篇: 3000字作文 小孩调皮