文档布局
只有当文档要在设备上显示时,或当某些信息的请求需要文档的可视化表示时,文档的布局才具有相关性。在此之前,文档不需要为设备进行格式化和准备。
概述
每个文档的布局都由QAbstractTextDocumentLayout 类的一个子类管理。该类为布局和渲染引擎提供了一个通用接口。默认的渲染行为目前是在一个私有类中实现的。这种方法使创建自定义布局成为可能,并为准备打印页面或导出为便携式文档格式 (PDF) 文件提供了机制。
示例--异形文本布局
有时,在不规则形状的区域内格式化纯文本非常重要,例如在渲染自定义 widget 时。Scribe 提供了通用功能,如QTextLayout 类提供的功能,帮助开发人员执行文字包装和布局任务,而无需先创建文档。
格式化和绘制一段纯文本非常简单。下面的示例将使用单一字体围绕圆的右边缘布局一段文本。
QTextLayout textLayout(text, font); qreal margin = 10; qreal radius = qMin(width()/2.0, height()/2.0) - margin; QFontMetrics fm(font); qreal lineHeight = fm.height(); qreal y = 0; textLayout.beginLayout(); while (1) { // create a new line QTextLine line = textLayout.createLine(); if (!line.isValid()) break; qreal x1 = qMax(0.0, pow(pow(radius,2)-pow(radius-y,2), 0.5)); qreal x2 = qMax(0.0, pow(pow(radius,2)-pow(radius-(y+lineHeight),2), 0.5)); qreal x = qMax(x1, x2) + margin; qreal lineWidth = (width() - margin) - x; line.setLineWidth(lineWidth); line.setPosition(QPointF(x, margin+y)); y += line.height(); } textLayout.endLayout(); QPainter painter; painter.begin(this); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(rect(), Qt::white); painter.setBrush(QBrush(Qt::black)); painter.setPen(QPen(Qt::black)); textLayout.draw(&painter, QPoint(0,0)); painter.setBrush(QBrush(QColor("#a6ce39"))); painter.setPen(QPen(Qt::black)); painter.drawEllipse(QRectF(-radius, margin, 2*radius, 2*radius)); painter.end();
我们创建一个文本布局,指定要显示的文本字符串和使用的字体。我们从文本格式中获取文本行,并利用可用空间将剩余文本包裹起来,以确保我们提供的文本格式正确。当我们向下移动页面时,这些行将被定位。
格式化后的文本可以绘制到绘画设备上;在上述代码中,文本是直接绘制到部件上的。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.