如何获取 QTextBlock 的行高

How to get the line height of a QTextBlock?

本文关键字:QTextBlock 获取 何获取      更新时间:2023-10-16

Windows 7 SP1
MSVS 2010
Qt 4.8.4

给定此代码:

#include <QTGui>
int main(int argc, char *argv[])
{
    QTextDocument* text_document = new QTextDocument("testing");
    QTextBlock text_block = text_document->begin();
    qDebug() << text_block.text() << text_block.blockFormat().lineHeight()
             << text_block.blockFormat().lineHeightType();
}

控制台显示:

"testing" 0 0

:为什么 lineHeight 不返回"段落的 LineHeight 属性"?lineHeightType 设置为单倍间距。

我显然不明白这一点。当我尝试在输出之前设置行高时,没有任何反应(lineHeight() 仍然为零):

text_block.blockFormat().setLineHeight(30,QTextBlockFormat::SingleHeight);

需要明确的是,在我的应用程序中,输出到 GUI 窗口时没有任何反应。

甚至尝试:

 qDebug() << text_block.text() << text_block.layout()->boundingRect().height();

给我零。

这是在小部件调用其 show() 函数之前还是之后完成的? IE,它们可见吗? 我以前从未使用过QTextBlock,但我发现在一切都可见之前(或者直到事件循环启动),我不能相信QWidgets的大小。 在 main() 中也是如此。

出于调试目的,我会在应用程序运行后检查它们。

我从来没有让lineHeight工作,但这确实如此:

int CalculateLineHeight(QTextBlock text_block)
{
    int max_ascent  = 0;
    int max_descent = 0;
    int max_leading = 0;
    // A fragment is a piece of the text block with the the same format, such as font.
    for (QTextBlock::Iterator fragment_it = text_block.begin(); !(fragment_it.atEnd()); ++fragment_it)
    {
        QTextFragment fragment = fragment_it.fragment();
        QTextCharFormat fragment_format = fragment.charFormat();
        QFont fragment_font = fragment_format.font();
        QFontMetrics fragment_font_metrics (fragment_font);
        max_ascent  = std::max(fragment_font_metrics.ascent(), max_ascent);
        max_descent = std::max(fragment_font_metrics.descent(),max_descent);
        // Find the leading of the font with the maximum height. If more than
        // one, then find the largest lead among them.
        if ( current_height > max_height )
        {
            max_height = current_height;
            max_leading = current_leading;
        }
        else if ( current_height == max_height && current_leading > max_leading )
        {
            max_leading = current_leading;
        }
    }
    return max_ascent + max_descent + max_leading + 1; // + 1 for the baseline
}

您可能认为答案是 max height(),但具有相同高度的字体可能具有不同的上升、下降和前导。