Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_gui_text_qtextlayout.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3#include <QFont>
4#include <QFontMetrics>
5#include <QPainter>
6#include <QTextLayout>
7#include <QTextLine>
8
10struct Wrapper : public QPaintDevice
11{
12 void wrapper1();
13 void elided();
14};
16
17
18void wrapper0() {
19qreal lineWidth = 0;
20QFont aFont;
21QFontMetrics fontMetrics(aFont);
22
23//! [0]
24int leading = fontMetrics.leading();
25qreal height = 0;
26textLayout.setCacheEnabled(true);
27textLayout.beginLayout();
28while (true) {
29 QTextLine line = textLayout.createLine();
30 if (!line.isValid())
31 break;
32
33 line.setLineWidth(lineWidth);
34 height += leading;
35 line.setPosition(QPointF(0, height));
36 height += line.height();
37}
38textLayout.endLayout();
39//! [0]
40
41} // wrapper0
42
43
45
46//! [1]
47QPainter painter(this);
48textLayout.draw(&painter, QPoint(0, 0));
49//! [1]
50
51} // Wrapper::wrapper1
52
53void Wrapper::elided() {
54
55QString content;
56
57//! [elided]
58QPainter painter(this);
59QFontMetrics fontMetrics = painter.fontMetrics();
60
61int lineSpacing = fontMetrics.lineSpacing();
62int y = 0;
63
64QTextLayout textLayout(content, painter.font());
65textLayout.beginLayout();
66while (true) {
67 QTextLine line = textLayout.createLine();
68
69 if (!line.isValid())
70 break;
71
72 line.setLineWidth(width());
73 const int nextLineY = y + lineSpacing;
74
75 if (height() >= nextLineY + lineSpacing) {
76 line.draw(&painter, QPoint(0, y));
77 y = nextLineY;
78 } else {
79 const QString lastLine = content.mid(line.textStart());
80 const QString elidedLastLine = fontMetrics.elidedText(lastLine, Qt::ElideRight, width());
81 painter.drawText(QPoint(0, y + fontMetrics.ascent()), elidedLastLine);
82 line = textLayout.createLine();
83 break;
84 }
85}
86textLayout.endLayout();
87//! [elided]
88}
89
90} // src_gui_text_qtextlayout