为了使图标与文本居中,您必须实现自己的代理样式来创建这种特定的样式行为。
#include <QProxyStyle>
#include <QPainter>
class HeaderProxyStyle : public QProxyStyle
{
public:
void drawControl(ControlElement oCtrElement, const QStyleOption * poStylrOptionption, QPainter * poPainter, const QWidget * poWidget = 0) const;
};
带有文本实现的中心图标
void HeaderProxyStyle::drawControl(ControlElement oCtrElement, const QStyleOption *poStylrOptionption, QPainter *poPainter, const QWidget *poWidget) const
{
// Header label?
if (oCtrElement == CE_HeaderLabel) {
// YES - Allocate style option header
QStyleOptionHeader *poStyleOptionHeader =
(QStyleOptionHeader *) poStylrOptionption;
// Get header icon
QIcon oIcon = qvariant_cast<QIcon>(poStyleOptionHeader->icon);
// Icon is valid?
if(oIcon.isNull()){
// No - Draw text header
QProxyStyle::drawControl(oCtrElement, poStylrOptionption, poPainter, poWidget);
return;
}
// Set icon size 16x16
QSize oIconSize = QSize(16,16);
// Get header section rect
QRect oRect = poStyleOptionHeader->rect;
// Create header icon pixmap
QPixmap oIconPixmap = oIcon.pixmap(oIconSize.width(),oIconSize.height());
// Calculate header text width
int iTextWidth = poStyleOptionHeader->fontMetrics.width(poStyleOptionHeader->text);
QRect oCenterRec = QRect(oRect.left(),
oRect.top() + (oRect.height - iTextSize)/2,
oIconPixmap.width(),oIconPixmap.height());
QRect oTextRect = QRect(oCenterRec.left()+ oIconSize.width(),
oCenterRec.top(), oCenterRec.width() + iTextWidth, oCenterRec.height());
// Draw icon
poPainter->drawPixmap(oCenterRec, oIconPixmap);
// Draw text
poPainter->drawText(oTextRect, poStyleOptionHeader->text);
return;
}
QProxyStyle::drawControl(oCtrElement, poStylrOptionption, poPainter, poWidget);
}
然后在树视图中应用此标题样式
// Set header style
m_treeview->header()->setStyle(&m_oHeaderStyle);