【问题标题】:How to know header text width in QStyle?如何知道 QStyle 中的标题文本宽度?
【发布时间】:2019-03-22 06:45:33
【问题描述】:

我有一个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 );
  }
}

我在这种情况下使用subElementRect( SE_HeaderLabel, p_option, p_widget ).width(),但这是错误的。如何计算文本的宽度?

【问题讨论】:

    标签: c++ qt qstyle


    【解决方案1】:

    全部包含在QStyleOptionHeader 中。文字宽度可以通过调用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 2014-11-18
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多