Qt 获取适合固定 QRect 的大 QString 的子串

Qt get substring of a large QString that fits inside fixed QRect

我有一个大字符串、一个固定的字体和一个固定的矩形来绘制该字符串。

我在网上搜索了一整天,一无所获。

使用 QFontMetrics class 及其 boundingRect class,获取提供的字符串所使用的矩形

// assumes myFont has been instantiated
QFontMetrics fm(myFont);
QRect bounds = fm.boundingRect("Some text here");

将边界大小与要测试字符串是否适合的区域进行比较。

If the string doesn't fit, I would like to know the length of substring that does fit into that rectangle

如果从 boundingRect 返回的矩形的边界太大,递归删除字符直到宽度适合您的目标矩形。

bool bFits = false;
QString str = "String to test boundary";
QFontMetrics fm(myFont);
QRect bounds;
do
{    
    bounds = fm.boundingRect(str);
    // Assume testBoundary is the defined QRect of the area to hold the text
    if(!testBoundary.contains(bounds) && (!str.isEmpty()) )
         str.chop(1);
    else
        bFits = true;
}while(!bFits);

if the string does fit, then I would like to know bounding rectangle height

这只是从调用 boundingRect 返回的矩形的高度。

int height = bounds.height();

我正在发布我自己的二进制搜索算法。 Batman指出了正确的方向,谢谢!

顺便说一句,如果你愿意,你可以使用 QFontMetrics 而不是 QPainter

int FontUtils::FittingLength(const QString& s, QPainter &p, const QRectF& rect,
                             int flags/* = Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap*/)
{
    QRectF r = p.boundingRect(rect, flags, s);
    if (r.height() <= rect.height()) // String fits rect.
        return s.length();

    // Apply binary search.
    QString sub;
    int left = 0, right = s.length()-1;
    do
    {
        int pivot = (left + right)>>1; // Middle point.
        sub = s.mid(0, pivot+1);
        r = p.boundingRect(rect, flags, sub);

        if (r.height() > rect.height()) // Doesn't fit.
            right = pivot-1;
        else
            left = pivot+1;
    } while (left < right);

    left++; // Length of string is one char more.

    // Remove trailing word if it doesn't fit.
    if  ( !s.at(left).isSpace() && !s.at(left+1).isSpace() )
    {
        while ( (--left > 0) && !sub.at(left).isSpace() );
        left++;
    }

    return left;
}