如何获取 QTextBlock 的行高
How to get the line height of a QTextBlock?
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(),但具有相同高度的字体可能具有不同的上升、下降和前导。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 具有默认值的引用获取函数
- 获取QPlainTextEdit中指向QTextBlock的指针
- 如何获取 QTextBlock 的行高