For Qt 4.6.x, how to auto-size text to fit in a specified width?

前端 未结 8 1086
情书的邮戳
情书的邮戳 2020-12-31 04:11

Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width

8条回答
  •  别那么骄傲
    2020-12-31 04:39

    Here is my code the fit (in heigth) a text, works quite well (error < 2% I guess)

    void scalePainterFontSizeToFit(QPainter &painter, QFont &r_font, float _heightToFitIn)
    {
        float oldFontSize, newFontSize, oldHeight;
    
        // Init
        oldFontSize=r_font.pointSizeF();
    
        // Loop
        for (int i=0 ; i<3 ; i++)
        {
            oldHeight = painter.fontMetrics().boundingRect('D').height();
            newFontSize = (_heightToFitIn / oldHeight) * oldFontSize;
            r_font.setPointSizeF(newFontSize);
            painter.setFont(r_font);
            oldFontSize = newFontSize;
            //qDebug() << "OldFontSize=" << oldFontSize << "HtoFitIn=" << _heightToFitIn << "  fontHeight=" << oldHeight << "  newFontSize=" << newFontSize;
        }
    
        // End
        r_font.setPointSizeF(newFontSize);
        painter.setFont(r_font);
    }
    

提交回复
热议问题