本页内容

文档布局

文档的版式仅在需要将其显示在设备上,或者需要获取某些需要通过文档可视化呈现的信息时才相关。在此之前,文档无需进行格式化处理,也无需为设备进行准备。

概述

每个文档的布局由QAbstractTextDocumentLayout 类的子类管理。该类为布局和渲染引擎提供了一个通用接口。默认的渲染行为目前实现于一个私有类中。这种方法使得创建自定义布局成为可能,并提供了在准备页面以供打印或导出为可移植文档格式(PDF)文件时所使用的机制。

示例——形状文本布局

有时,能够在不规则形状的区域内对纯文本进行格式化非常重要,例如在渲染自定义控件时。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();

我们创建一个文本布局,指定要显示的文本字符串以及要使用的字体。通过从文本格式中获取文本行,并利用可用空间对剩余文本进行换行,确保所提供的文本格式正确。随着页面向下滚动,这些行会被依次定位。

格式化的文本可以绘制到绘图设备上;在上述代码中,文本被直接绘制到小部件上。

© 2026 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.