C++ 如何知道QStyle中的标题文本宽度?

C++ 如何知道QStyle中的标题文本宽度?,c++,qt,qstyle,C++,Qt,Qstyle,我有一个QTreeView并使用ProxyStyle 上面的图片只是标题。现在,我需要在标题标签旁边绘制上/下箭头(用于排序项目),如图所示。为了将箭头放置在正确的位置,我需要知道: 左边距=文本和左边框之间的距离 文本宽度 右边距=文本和箭头之间的距离 在这种情况下,如何计算文本宽度?我考虑过QFontMetrics,但不知道如何接收文本进行计算 在我的风格中,我只使用drawPrimitive函数 void MyStyle::drawPrimitive( PrimitiveElemen

我有一个
QTreeView
并使用
ProxyStyle

上面的图片只是标题。现在,我需要在标题标签旁边绘制上/下箭头(用于排序项目),如图所示。为了将箭头放置在正确的位置,我需要知道:

  • 左边距=文本和左边框之间的距离
  • 文本宽度
  • 右边距=文本和箭头之间的距离
在这种情况下,如何计算文本宽度?我考虑过QFontMetrics,但不知道如何接收文本进行计算

在我的风格中,我只使用
drawPrimitive
函数

void MyStyle::drawPrimitive( PrimitiveElement p_pe, const QStyleOption *p_option, QPainter *p_painter, const QWidget *p_widget ) const
{
  int leftmargin = 10;
  int rightmargin = 10;
  if ( p_pe == PE_IndicatorHeaderArrow )
  {
     if ( const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>( p_option ) )
     {
        QPixmap pix;
        if ( header->sortIndicator & QStyleOptionHeader::SortUp )
        {
           pix = QPixmap( ":/sortUp.png" );
        }
        else if ( header->sortIndicator & QStyleOptionHeader::SortDown )
        {
           pix = QPixmap( ":/sortDown.png" );
        }
        p_painter->drawPixmap( header->rect.left() + leftmargin+ subElementRect( SE_HeaderLabel, p_option, p_widget ).width() + rightmargin, header->rect.top() + pix.height(), pix );
     }
  }
  else
  {
     QProxyStyle::drawPrimitive( p_pe, p_option, p_painter, p_widget );
  }
}
void MyStyle::drawPrimitive(原语元素p_pe,常量QStyleOption*p_option,QPainter*p_painter,常量QWidget*p_widget)const
{
int leftmargin=10;
int rightmargin=10;
if(p_-pe==pe_指示器箭头)
{
if(常量QStyleOptionHeader*header=qstyleoption\u cast(p\u选项))
{
QPixmap-pix;
if(标题->排序指示器&QStyleOptionHeader::SortUp)
{
pix=QPixmap(:/sortUp.png”);
}
else if(标题->排序指示器&QStyleOptionHeader::SortDown)
{
pix=QPixmap(:/sortDown.png”);
}
p_painter->drawPixmap(页眉->矩形左()+左边距+子元素矩形(SE_页眉标签,p_选项,p_小部件)。宽度()+右边距,页眉->矩形顶部()+像素高度(),像素);
}
}
其他的
{
QProxyStyle::drawPrimitive(p_pe、p_选项、p_画师、p_小部件);
}
}

在这种情况下,我使用
subElementRect(SE\u HeaderLabel,p\u选项,p\u小部件).width()
,但它是错误的。如何计算文本的宽度?

它都包含在文档中。可通过调用以下命令获取文本宽度:

int textWidth = header->fontMetrics.boundingRect(header->text).width();