文書のレイアウト
文書のレイアウトは、デバイス上に表示される場合、または文書の視覚的な表現を必要とする情報が要求される場合にのみ重要となります。それまでは、文書をデバイス用にフォーマットしたり準備したりする必要はありません。
概要
各ドキュメントのレイアウトは、QAbstractTextDocumentLayout クラスのサブクラスによって管理されます。このクラスは、レイアウトおよびレンダリングエンジン向けの共通インターフェースを提供します。デフォルトのレンダリング動作は、現在プライベートクラスで実装されています。このアプローチにより、カスタムレイアウトの作成が可能となり、印刷やPortable Document Format(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.