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();
给我零。
答案 0 :(得分:0)
这是在小部件调用了show()函数之前还是之后完成的? IE,它们可见吗?我以前从未使用过QTextBlock,但我发现在所有内容都可见之前(或者可能直到事件循环开始),我不相信QWidgets的大小。这在main()中是正确的。
出于调试目的,我会在应用程序运行后检查它们。
答案 1 :(得分:0)
我从来没有得到行高,但这样做:
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
}
您可能认为答案是最大高度(),但具有相同高度的字体可能有不同的上升,下降和前导。